先解決一下IDEA使用遠(yuǎn)程解釋器,本地代碼編輯無法代碼提示問題
常用的4個Python Web框架對比
一、Flask入門案例 官網(wǎng) 其它參考
注意
1.這里使用linux 192.168.72.126上遠(yuǎn)程解釋器,需要/usr/bin/pip3 install flask
,host參數(shù)不要使用localhost/127.0.0.1,即只監(jiān)聽本地的訪問,會導(dǎo)致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
from flask import Flask
app=Flask(__name__)
@app.route('/test1')
def test1():
return 'hello flask!'
"""
返回模板,并在模板中使用類似VUE的模板語法取數(shù)據(jù)
"""
@app.route('/test2',methods=['GET'])
def test2():
from flask import render_template
return render_template("index.html",data="傳入html模板的數(shù)據(jù)")
"""
返回json str,Content-Type默認(rèn)為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入門案例 官網(wǎng) w3cschool教程
注意:
pip3 install fastapi "uvicorn[standard]"
,需要安裝uviron來運行fastapi- 也支持類似flask的uvicorn命令啟動
cd /tmp/pycharm_project_22 && uvicorn testflask:app --reload --host 0.0.0.0 --port 2023
,–reload熱加載- 自帶swagger API文檔
http://192.168.72.126:2023/docs
- 如報錯無法import pydantic 相關(guān)錯誤,可以https://pypi.org/下載pydantic的離線whl包進(jìn)行安裝
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
# -*- 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):
"""對應(yīng)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邏輯核數(shù)個業(yè)務(wù)進(jìn)程
tornado.ioloop.IOLoop.current().start()
四、Django入門案例 菜鳥教程
1.pip3 install django
2.IDEA創(chuàng)建python項目可以選中django框架直接創(chuàng)建django項目骨架,也可以使用django-admin來創(chuàng)建django-admin startproject HelloWorld
,新增接口,并在urls.py配置路由
文章來源:http://www.zghlxwxcb.cn/news/detail-584111.html
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),
]
運行文章來源地址http://www.zghlxwxcb.cn/news/detail-584111.html
到了這里,關(guān)于試玩python的web框架 flask、fastapi、tornado、django的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!