pip3 install flask
mkdir ~/test-flask
cd ~/test-flask
touch server.py
设定GET方法返回基于当天日期的随机词汇样本,POST方法接受一个日期参数,返回基于该日期参数的随机词汇样本:
from flask import Flask, jsonify, request
from datetime import datetime
import random
app = Flask(__name__)
# IELTS词汇数据库
IELTS_VOCAB = [
{"word": "abide", "usage": "To abide by the rules."},
{"word": "accentuate", "usage": "To accentuate a point."},
# ... 更多词汇 ...
]
@app.route('/vocab/daily', methods=['GET'])
def get_daily_vocab_samples():
# 设定随机种子为当前日期
seed_str = datetime.now().strftime('%Y%m%d')
return get_vocab_samples_by_seed(seed_str)
@app.route('/vocab/by-date', methods=['POST'])
def get_vocab_samples_by_provided_date():
# 从POST请求中获取日期参数
try:
date_str = request.json.get('date', '')
if not date_str:
return jsonify(error="Missing 'date' parameter."), 400
# 验证日期格式,需要使用YYYYMMDD格式
if not date_str.isdigit() or len(date_str) != 8:
return jsonify(error="Invalid 'date' format. Use YYYYMMDD."), 400
except Exception as e:
return jsonify(error=f"An error occurred: {str(e)}."), 400
# 使用提供的日期作为随机种子
return get_vocab_samples_by_seed(date_str)
def get_vocab_samples_by_seed(seed_str):
random.seed(seed_str)
samples = random.sample(IELTS_VOCAB, min(5, len(IELTS_VOCAB)))
return jsonify(samples)
if __name__ == '__main__':
app.run(host='0.0.0.0', debug=True)
两个路由:
/vocab/daily
基于当前日期进行抽样(使用GET方法)/vocab/by-date
根据提供的日期进行抽样(使用POST方法,需要有参数date)启动server:
python3 server.py
# export FLASK_APP=server.py
# flask run
访问 localhost:5000/vocab/daily
可以得到JSON响应
curl localhost:5000/vocab/daily
使用curl发送一个包含date
参数的JSON请求体:
curl -X POST http://localhost:5000/vocab/by-date -H "Content-Type: application/json" -d '{"date": "20550505"}'
vocab.json
存储了一些元祖:
[{"word": "apple", "usage": "The apple is a sweet and juicy fruit."}, {"word": "banana", "usage": "Bananas are a popular tropical fruit."}, {"word": "cat", "usage": "Cats are small domesticated carnivores."}, {"word": "dog", "usage": "Dogs are loyal and friendly pets."}, {"word": "elephant", "usage": "Elephants are large mammals with long noses."}, {"word": "fish", "usage": "Fish live in water and breathe through gills."}, {"word": "grape", "usage": "Grapes are small, sweet fruits used to make wine."}, {"word": "house", "usage": "A house is a building where people live."}, {"word": "ice cream", "usage": "Ice cream is a sweet dessert made from cream and sugar."}, {"word": "jungle", "usage": "A jungle is a dense tropical forest."}, {"word": "kangaroo", "usage": "Kangaroos are marsupials native to Australia."}, {"word": "lion", "usage": "Lions are the kings of the jungle and fierce predators."}, {"word": "mountain", "usage": "Mountains are large natural elevations on the Earth."}, {"word": "ocean", "usage": "The ocean covers most of the Earth and contains many marine creatures."}, {"word": "parrot", "usage": "Parrots are colorful birds with the ability to talk."}, {"word": "rainbow", "usage": "A rainbow is a circular arc in the sky with colors."}, {"word": "school", "usage": "A school is a place where children learn."}, {"word": "sun", "usage": "The sun is a star that provides light and heat to the Earth."}, {"word": "tiger", "usage": "Tigers are striped cats and powerful predators."}, {"word": "tree", "usage": "Trees are large plants with trunks and branches."}, {"word": "zebra", "usage": "Zebras are horses with black and white stripes."}]
from flask import Flask, jsonify, request
from datetime import datetime
import random
import json
import os
app = Flask(__name__)
# IELTS词汇数据库JSON文件路径
IELTS_VOCAB_FILE = 'vocab.json'
# 加载IELTS词汇元祖
def load_ielts_vocab():
if not os.path.exists(IELTS_VOCAB_FILE):
return []
with open(IELTS_VOCAB_FILE, 'r') as file:
return json.load(file)
# 根据日期生成随机种子,返回随机样本
def get_vocab_samples_by_seed(seed_str, vocab_list):
if not vocab_list:
return jsonify({'error': 'IELTS vocabulary list is empty.'}), 400
random.seed(seed_str)
samples = random.sample(vocab_list, min(5, len(vocab_list)))
return jsonify(samples)
@app.route('/vocab/daily', methods=['GET'])
def get_daily_vocab_samples():
seed_str = datetime.now().strftime('%Y%m%d')
vocab_list = load_ielts_vocab()
return get_vocab_samples_by_seed(seed_str, vocab_list)
@app.route('/vocab/by-date', methods=['POST'])
def get_vocab_samples_by_provided_date():
try:
data = request.get_json(force=True)
date_str = data.get('date', '')
if not date_str or not date_str.isdigit() or len(date_str) != 8:
return jsonify({'error': 'Invalid "date" format. Use YYYYMMDD.'}), 400
vocab_list = load_ielts_vocab()
return get_vocab_samples_by_seed(date_str, vocab_list)
except Exception as e:
return jsonify({'error': f'An error occurred: {str(e)}'}), 400
if __name__ == '__main__':
app.run(host='0.0.0.0', debug=True)
pip3 install -U Flask-SQLAlchemy
使用sqlite存储json数据
import sqlite3
import json
conn = sqlite3.connect('vocab.db')
cursor = conn.cursor()
# 创建表(如果表不存在)
cursor.execute('''
CREATE TABLE IF NOT EXISTS vocab (
id INTEGER PRIMARY KEY AUTOINCREMENT,
word TEXT NOT NULL,
usage TEXT NOT NULL
)
''')
with open('vocab.json', 'r') as f:
vocab_data = json.load(f)
for entry in vocab_data:
word = entry['word']
usage = entry['usage']
cursor.execute("INSERT INTO vocab (word, usage) VALUES (?, ?)", (word, usage))
# 提交事务
conn.commit()
# 关闭连接
conn.close()
print("success")
使用SQLAlchemy查询数据库:
from flask import Flask, jsonify, request
from flask_sqlalchemy import SQLAlchemy
from datetime import datetime
import random
app = Flask(__name__)
# 配置SQLAlchemy数据库
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///vocab.db'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db = SQLAlchemy(app)
# 定义数据库模型
class Vocab(db.Model):
id = db.Column(db.Integer, primary_key=True)
word = db.Column(db.String(80), unique=True, nullable=False)
usage = db.Column(db.Text, nullable=False)
# 初始化数据库,创建表格(如果尚不存在)
with app.app_context():
db.create_all()
@app.route('/vocab/daily', methods=['GET'])
def get_daily_vocab_samples():
seed_str = datetime.now().strftime('%Y%m%d')
return get_vocab_samples_by_seed(seed_str)
@app.route('/vocab/by-date', methods=['POST'])
def get_vocab_samples_by_provided_date():
try:
date_str = request.json.get('date', '')
if not date_str:
return jsonify(error="Missing 'date' parameter."), 400
if not date_str.isdigit() or len(date_str) != 8:
return jsonify(error="Invalid 'date' format. Use YYYYMMDD."), 400
except Exception as e:
return jsonify(error=f"An error occurred: {str(e)}."), 400
# 使用提供的日期作为随机种子
return get_vocab_samples_by_seed(date_str)
def get_vocab_samples_by_seed(seed_str):
random.seed(seed_str)
# sampling
samples = Vocab.query.order_by(db.func.random()).limit(5).all()
return jsonify([{'word': sample.word, 'usage': sample.usage} for sample in samples])
if __name__ == '__main__':
# 如果vocab.db不存在,会自动创建
with app.app_context():
db.create_all()
app.run(host='0.0.0.0', debug=True)
netstat -tupln | grep ':5000'
iptables -I INPUT -p tcp --dport 5000 -j ACCEPT
firewall-cmd --permanent --add-port=5000/tcp
firewall-cmd --reload
浏览器访问:
http://192.168.56.106:5000/vocab/daily
测试post method:
# run in git bash
curl -X POST http://192.168.56.106:5000/vocab/by-date -H "Content-Type: application/json" -d '{"date": "20550505"}'
const axios = require('axios');
const url = 'http://192.168.56.106:5000/vocab/by-date';
const data = { date: '20550505' };
axios.post(url, data)
.then(response => console.log(response))
.catch(error => console.log(error));
下载Postman:
win64: https://dl.pstmn.io/download/latest/win64
linux64: https://dl.pstmn.io/download/latest/linux64
导入curl命令:
curl --location 'http://192.168.56.106:5000/vocab/by-date' \
--header 'Content-Type: application/json' \
--data '{"date": "20550505"}'
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。