试玩python的web框架 flask、fastapi、tornado、django

文章目录

先解决一下IDEA使用远程解释器,本地代码编辑无法代码提示问题

常用的4个Python Web框架对比

一、Flask入门案例 官网 其它参考

注意

1.这里使用linux 192.168.72.126上远程解释器,需要/usr/bin/pip3 install flask,host参数不要使用localhost/127.0.0.1,即只监听本地的访问,会导致windows无法访问到flask app

2.运行方式增加main方法入口,使用python运行;或使用flask命令运行export FLASK_APP=/tmp/pycharm_project_22/testflask.py然后 flask run --host 0.0.0.0 --port 2023

python 复制代码
from flask import  Flask
app=Flask(__name__)


@app.route('/test1')
def test1():
    return 'hello flask!'

"""
返回模板,并在模板中使用类似VUE的模板语法取数据
"""
@app.route('/test2',methods=['GET'])
def test2():
    from flask import  render_template
    return render_template("index.html",data="传入html模板的数据")

"""
返回json str,Content-Type默认为application/html,需要指定为json
"""
@app.route('/test3',methods=['GET'],)
def test3():
    import json
    json_str = json.dumps({"a": 1, "b": "2"})
    return json_str, 200, {"Content-Type":"application/json"}


if __name__=="__main__":
    app.run(port=2023,host="0.0.0.0",debug=True)

二、FastAPI入门案例 官网 w3cschool教程

注意:

  1. pip3 install fastapi "uvicorn[standard]" ,需要安装uviron来运行fastapi
  2. 也支持类似flask的uvicorn命令启动 cd /tmp/pycharm_project_22 && uvicorn testflask:app --reload --host 0.0.0.0 --port 2023 ,--reload热加载
  3. 自带swagger API文档http://192.168.72.126:2023/docs
  4. 如报错无法import pydantic 相关错误,可以https://pypi.org/下载pydantic的离线whl包进行安装
python 复制代码
from fastapi import FastAPI
app = FastAPI()


@app.get("/test1")
def test1():
    return "hello fastapi"

@app.get("/test2")
def test2():
    return {"a": 1, "b": 2}

if __name__=="__main__":
    import uvicorn
    uvicorn.run(app=app,host="0.0.0.0",port=2023)

三、Tornado入门案例 参考

pip3 install tornado

py 复制代码
# -*- coding: utf-8 -*-
import tornado.options

tornado.options.define("port", default=8000, type=int, help="specify your app port")


class Test1(tornado.web.RequestHandler):
    def get(self):
        self.write("hello1!")


class Test2(tornado.web.RequestHandler):
    """对应http的get请求方式!!!!!"""

    def get(self):
        self.write("hello2!")


if __name__ == "__main__":
    tornado.options.parse_command_line()
    app = tornado.web.Application([("/test1", Test1), ("/test2", Test2)])
    http_server = tornado.httpserver.HTTPServer(app)
    http_server.bind(tornado.options.options.port)
    http_server.start(0)  # <=0时会拉起CPU逻辑核数个业务进程
    tornado.ioloop.IOLoop.current().start()

四、Django入门案例 菜鸟教程

1.pip3 install django

2.IDEA创建python项目可以选中django框架直接创建django项目骨架,也可以使用django-admin来创建django-admin startproject HelloWorld ,新增接口,并在urls.py配置路由

py 复制代码
from django.contrib import admin
from django.urls import path
from . import test
urlpatterns = [
    path('admin/', admin.site.urls),
    path('hello1', test.hello1),
    path('hello2', test.hello2),
]

运行

相关推荐
qq_161111272 小时前
Jenkins+Python自动化测试持续集成详细教程
自动化测试·python·jenkins·教程·持续集成
爱吃苹果的梨叔5 小时前
训练集群网络中断怎么办?智算机房的 Console 串口排障方案
网络·python·智能路由器·php
李妍.8 小时前
02Numpy基础(上)
开发语言·python
TheBestRucy8 小时前
Python 九阳神功之贰:面向对象(下)
开发语言·python
2601_965958469 小时前
口腔黏膜脱皮超2周未愈建议及时就医
人工智能·python
微小冷10 小时前
在不同空间中展示数据(欧式、球面、庞加莱圆盘)
python·双曲空间·微分几何·geomstats·庞加莱圆盘·球面
weixin_4316004410 小时前
Agent Workflow 学习向:Code 节点,比模板更强的变量加工
后端·python·学习·ai·
讲温控就好了10 小时前
从医疗影像到能源存储——芯片冷却温控技术的跨行业赋能
人工智能·python·能源
DeepVisionary11 小时前
从 Qwen3.8-27B 把原生多模态、原生 FP8、桌面级 Agent 三件事一次集齐,看开源大模型的“工业化拐点“
python·自动化
固定资产管理系统软件12 小时前
商务局RFID固定资产管理系统的应用价值与落地要点解析
大数据·python