四、Flask快速入门

15天前 阅读 21 评论 0 赞 0

Flask快速入门

wsgi,werkzeug

通过werkzeug:

  1. from werkzeug.wrappers import Request, Response
  2. @Request.application
  3. def hello(request):
  4. return Response('Hello World!')
  5. if __name__ == '__main__':
  6. from werkzeug.serving import run_simple
  7. run_simple('localhost', 4000, hello)

可以简单实现一个web框架的网站

通过wsgiref也可以:

  1. from wsgiref.simple_server import make_server
  2. def runserver(environ, start_response):
  3. start_response('200 OK', [('Content-Type', 'text/html')])
  4. return [bytes('<h1>Hello, web!</h1>', encoding='utf-8'), ]
  5. if __name__ == '__main__':
  6. httpd = make_server('', 8000, runserver)
  7. httpd.serve_forever()

本质的本质:

  1. import socket
  2. def handle_request(client):
  3. buf = client.recv(1024)
  4. client.send("HTTP/1.1 200 OK\r\n\r\n")
  5. client.send("Hello, Seven")
  6. def main():
  7. sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  8. sock.bind(('localhost',8000))
  9. sock.listen(5)
  10. while True:
  11. connection, address = sock.accept()
  12. handle_request(connection)
  13. connection.close()
  14. if __name__ == '__main__':
  15. main()
  16. flask
  17. from flask import Flask
  18. app = Flask(__name__)
  19. @app.route('/') # 1. v=app.route(‘/’) 2.v(hello_world)
  20. def hello_world():
  21. return 'Hello World!'
  22. if __name__ == '__main__':
  23. app.run()

图片6
模板路径为templates
url数据在request.querystring中,form数据在request.form中放着
endpoint、url_for合用是反向生成url

写装饰器用于用户认证:

多个装饰器
url别名不允许重复

你的支持将鼓励作者继续创作

评论(0)

(无)