备忘性质的一篇博客。记录用flask对Python封装成API的学习及问题解决过程。
关于我:纯纯小白,只会用Python封装exe,虽然考过什么全国计算机三级网络技术,但是十年前了,对各种ip网关啥的一窍不通。
学习参考
Flask 1.1.1 中文文档:https://flask.net.cn/(我也不知道是不是最新的,但是用着还可以)
虚拟环境搭建
软件:pycharm2022、apifox
也不知道怎么用,就跟着教程搭建了一个叫myproject的虚拟环境:
![](https://i-blog.csdnimg.cn/blog_migrate/d61fea199b836e58416687c3c64e85b7.png)
关键程序:
![](https://i-blog.csdnimg.cn/blog_migrate/0e980fd60a7a79746133f1505e3bca6a.png)
上手一个最小的应用
主程序:hello.py
from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello_world():
return 'Hello, World!'
运行:
需要跳回到主程序所在目录下:
set FLASK_APP=hello.py
// $env:FLASK_APP = "hello.py"
flask run
![](https://i-blog.csdnimg.cn/blog_migrate/6ee02e3d0c3bd7e8774aa7da2089967a.png)
有个WARNING,尝试解决没成功,先搁置吧,看看后面有没有影响。
点击网址得到:
![](https://i-blog.csdnimg.cn/blog_migrate/1ad64bc8606821416b9864c1b4fff117.png)
其中:FLASK_ENV=development是调试模式,不能用在生产环境中。
改URL名字!
可以通过改这里:@app.route('/')
from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello_world():
return 'Hello, World!'
@app.route('/name')
def get_name():
return 'hcy'
@app.route('/fans')
def get_fans():
return "10000"
结果比如:
![](https://i-blog.csdnimg.cn/blog_migrate/bc080ed1089db27da9d8d4714fb67dfd.png)
注意:
The return type must be a string, dict, list, tuple with headers or status, Response instance, or WSGI callable
学习POST
from flask import Flask, escape, url_for
from flask import request
app = Flask(__name__)
@app.route('/', methods=['GET', 'POST'])
def index():
return 'index'
@app.route('/login', methods=['GET', 'POST'])
def login():
if request.method == 'POST':
return "hcy from post"
else:
return 'hcy from get'
![](https://i-blog.csdnimg.cn/blog_migrate/5a8f6d7f643485fe29ab4389d9516bb4.png)
post json结构化数据
@app.route('/test_json', methods=['GET', 'POST'])
def test_json():
if request.method == 'POST':
print(request.json)
return "hcy from post"
elif request.method == 'GET':
return dict(name='hcy', do='test')
![](https://i-blog.csdnimg.cn/blog_migrate/d7c685888d13aca5c63f07e4f0e8b2e5.png)
从postman获取json,并返回
@app.route('/test_json', methods=['GET', 'POST'])
def test_json():
if request.method == 'POST':
print(request.json)
print(request.form)
print(request.data)
name = request.json.get('name')
if name == 'hcy':
return {'my name':'hcy', 'judge':'yes'}
return "hcy from post"
elif request.method == 'GET':
return dict(name='hcy', do='test')
![](https://i-blog.csdnimg.cn/blog_migrate/c1b2d927c905c08805f9cfc7a6d39c60.png)