API 模块

网站想开放 API 接口供别人使用

创建一个 Web 接口服务,例如使用 Python 的 Flask 框架。

开放一个返回当前时间的 API 接口

1
2
3
4
5
6
7
8
9
10
11
12
from flask import Flask, jsonify
from datetime import datetime

app = Flask(__name__)

@app.route('/api/time', methods=['GET'])
def get_time():
now = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
return jsonify({"time": now})

if __name__ == '__main__':
app.run(host='0.0.0.0', port=5000)

使用 fastapi

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
from fastapi import FastAPI
import random


app = FastAPI()

@app.get("/")
async def root():
return {'message': "Hello World", 'data': 0}


@app.get("/random/{limit}")
async def get_random(limit: int):
rn:int = random.randint(0, limit) # 这个范围是0-limit,并且包含0和limit
return {'number': rn, 'limit': limit}

@app.get("/random/")
async def get_random():
rn:int = random.randint(0, 100) # 这个范围是0-limit,并且包含0和limit
return {'number': rn, 'limit': 100}

启动命令

1
uvicorn main:app --reload
  • uvicorn:命令启动 uvicorn 服务器
  • main:main.py 文件
  • app:app 变量
  • –reload:自动重启 热更新