十四个Python Web框架Hello Wold示例
1、Dganjo
新建一个django项目,HelloWorld
mkdir django
cd django
django-admin startproject HelloWorld #新建项目
cd HelloWorld
python manage.py startapp Hello #新建应用
vim Hello/views.py
#coding=utf-8
from django.shortcuts import render
from django.http import HttpResponse
def index(req):
return HttpResponse('Hello World!')
vim HelloWorld/HelloWorld/urls.py
from django.conf.urls import url
from django.contrib import admin
from Hello import views as Hello_views
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^$', Hello_views.index),
]
vim HelloWorld/HelloWorld/settings.py
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'Hello',
]
运行启动命令:
python manage.py runserver
2、Flask
from flask import Flask
app = Flask(__name__)
@app.route("/")
def hello_world():
return "Hello, World!"
if __name__ == '__main__':
app.run(debug=True)
3、Pyramid
from wsgiref.simple_server import make_server
from pyramid.config import Configurator
from pyramid.response import Response
def hello_world(request):
return Response('Hello World!')
if __name__ == '__main__':
with Configurator() as config:
config.add_route('hello', '/')
config.add_view(hello_world, route_name='hello')
app = config.make_wsgi_app()
server = make_server('0.0.0.0', 6543, app)
server.serve_forever()
4、web.py
import web
urls = (
'/(.*)', 'hello'
)
app = web.application(urls, globals())
class hello:
def GET(self, name):
if not name:
name = 'World'
return 'Hello, ' + name + '!'
if __name__ == "__main__":
app.run()
5、Tornado
import tornado.ioloop
import tornado.web
class MainHandler(tornado.web.RequestHandler):
def get(self):
self.write("Hello, world!")
def make_app():
return tornado.web.Application([
(r"/", MainHandler),
])
if __name__ == "__main__":
app = make_app()
app.listen(8888)
tornado.ioloop.IOLoop.current().start()
6、TurboGears
from wsgiref.simple_server import make_server
from tg import MinimalApplicationConfigurator
from tg import expose, TGController
# RootController of our web app, in charge of serving content for /
class RootController(TGController):
@expose(content_type="text/plain")
def index(self):
return 'Hello World!'
# Configure a new minimal application with our root controller.
config = MinimalApplicationConfigurator()
config.update_blueprint({
'root_controller': RootController()
})
# Serve the newly configured web application.
print("Serving on port 8080...")
httpd = make_server('', 8080, config.make_wsgi_app())
httpd.serve_forever()
7、CherryPy
import cherrypy
class HelloWorld(object):
@cherrypy.expose
def index(self):
return 'Hello World!'
cherrypy.config.update({'server.socket_host': '0.0.0.0'})
cherrypy.quickstart(HelloWorld(), '/')
8、Falcon
from wsgiref.simple_server import make_server
import falcon
class ThingsResource(object):
def on_get(self, req, resp):
resp.status = falcon.HTTP_200
resp.body = 'Hello world!\n'
app = falcon.App()
things = ThingsResource()
app.add_route('/things', things)
if __name__ == '__main__':
with make_server('', 8000, app) as httpd:
print('Serving on port 8000...')
httpd.serve_forever()
9、Asgineer
import asgineer
@asgineer.to_asgi
async def hello_word(request):
path = request.path
if path == '/':
return f"<html>Hello world! <b>{request.path}</b></html>"
if __name__ == '__main__':
asgineer.run('uvicorn', hello_word, 'localhost:8080')
10、Bottle
from bottle import route, run, template
@route('/hello/<name>')
def index(name):
return template('<b>Hello {{name}}</b>!', name=name)
run(host='localhost', port=8080)
11、Twisted
from twisted.web import server, resource
from twisted.internet import reactor, endpoints
class Counter(resource.Resource):
isLeaf = True
numberRequests = "Hello World!"
def render_GET(self, request):
self.numberRequests += 1
request.setHeader(b"content-type", b"text/plain")
content = u"{}\n".format(self.numberRequests)
return content.encode("ascii")
endpoints.serverFromString(reactor, "tcp:8080").listen(server.Site(Counter()))
reactor.run()
12、Hug
import hug
@hug.get('/')
def happy_birthday():
return "Hello World!"
hug -f hello_world.py
13、FastAPI
from typing import Optional
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
def read_root():
return {"Hello": "World"}
@app.get("/items/{item_id}")
def read_item(item_id: int, q: Optional[str] = None):
return {"item_id": item_id, "q": q}
uvicorn main:app --reload
14、Quart
from quart import Quart
app = Quart(__name__)
@app.route('/')
async def hello():
return 'Hello World!'
app.run()