前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >简单定义Flask接口

简单定义Flask接口

原创
作者头像
esse LL
修改2024-03-23 07:23:42
1910
修改2024-03-23 07:23:42
举报
文章被收录于专栏:操作系统实验

在Flask中定义简单的get和post路由

1. 安装Flask

代码语言:bash
复制
pip3 install flask
mkdir ~/test-flask
cd ~/test-flask
touch server.py

2. 定义接口

设定GET方法返回基于当天日期的随机词汇样本,POST方法接受一个日期参数,返回基于该日期参数的随机词汇样本:

代码语言:python
代码运行次数:0
复制
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)

两个路由:

  1. /vocab/daily 基于当前日期进行抽样(使用GET方法)
  2. /vocab/by-date 根据提供的日期进行抽样(使用POST方法,需要有参数date)

3. 测试接口

启动server:

代码语言:shell
复制
python3 server.py
# export FLASK_APP=server.py
# flask run

访问 localhost:5000/vocab/daily 可以得到JSON响应

代码语言:bash
复制
curl localhost:5000/vocab/daily

使用curl发送一个包含date参数的JSON请求体:

代码语言:bash
复制
curl -X POST http://localhost:5000/vocab/by-date -H "Content-Type: application/json" -d '{"date": "20550505"}'

4. 使用JSON数据文件

vocab.json 存储了一些元祖:

代码语言: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."}]
代码语言:python
代码运行次数:0
复制
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)

5. 使用关系型数据库

代码语言:bash
复制
pip3 install -U Flask-SQLAlchemy

使用sqlite存储json数据

代码语言:python
代码运行次数:0
复制
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查询数据库:

代码语言:python
代码运行次数:0
复制
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)

6. 局域网访问

代码语言:bash
复制
netstat -tupln | grep ':5000'
iptables -I INPUT -p tcp --dport 5000 -j ACCEPT
firewall-cmd --permanent --add-port=5000/tcp
firewall-cmd --reload

浏览器访问:

代码语言:bash
复制
http://192.168.56.106:5000/vocab/daily

测试post method:

代码语言:bash
复制
# run in git bash
curl -X POST http://192.168.56.106:5000/vocab/by-date -H "Content-Type: application/json" -d '{"date": "20550505"}'
代码语言:javascript
复制
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));

7. 使用Postman测试

下载Postman:

win64: https://dl.pstmn.io/download/latest/win64

linux64: https://dl.pstmn.io/download/latest/linux64

导入curl命令:

代码语言:bash
复制
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 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 在Flask中定义简单的get和post路由
    • 1. 安装Flask
      • 2. 定义接口
        • 3. 测试接口
          • 4. 使用JSON数据文件
            • 5. 使用关系型数据库
              • 6. 局域网访问
                • 7. 使用Postman测试
                相关产品与服务
                数据库
                云数据库为企业提供了完善的关系型数据库、非关系型数据库、分析型数据库和数据库生态工具。您可以通过产品选择和组合搭建,轻松实现高可靠、高可用性、高性能等数据库需求。云数据库服务也可大幅减少您的运维工作量,更专注于业务发展,让企业一站式享受数据上云及分布式架构的技术红利!
                领券
                问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档