【Flask】初识Flask

幸鸿轩
2023-12-01
  • 什么是Flask
    Flask是一款在Python开发中可以使用的Web框架,其特点是短小精悍,可扩展性强
  • Flask依赖wsgi
    web服务网关接口,wsgi是一个协议,其相关模块有wsgiref与werkzeug
    实现其协议的模块本质上就是socket服务端用于接收用户请求,并处理。
    一般web框架基于wsgi实现,这样实现关注点分离。
  • wsgi通俗来讲,其本质是socket,封装了socket的相关操作(比如端口, send, receive等)。Flask因为是Web框架,需要请求响应自然也依赖于wsgi。Flask依赖于第三方wsgi,名叫werkzurg先看看werkzurg的两个简单示例
#示例一:还需要对请求,响应作处理
from werkzeug.serving import run_simple

def run(environ,start_response):
   return [b"asdfasdf"]

if __name__ == '__main__':
   run_simple('localhost', 4000, run)  #第三个参数除了填函数名外,还可以填类的对象名,若为对象名,在执行时会执行,对象(),此时会调用类对象中的__call__方法

#示例一:已经对请求做了处理
from werkzeug.wrappers import Response
from werkzeug.serving import run_simple

def run_server(environ, start_response):
    response = Response('hello')
    return response(environ, start_response)

if __name__ == '__main__':
    run_simple('127.0.0.1', 8000, run_server)
#示例二:  
from werkzeug.wrappers import Request, Response

@Request.application
def hello(request):
    return Response('Hello World!')

if __name__ == '__main__':
    from werkzeug.serving import run_simple
    run_simple('localhost', 4000, hello)

补充:在对象后加括号会执行什么

class Foo(object):

    def __init__(self):
        print('sdfsdf')

    def __call__(self, *args, **kwargs):
        print('call')

obj = Foo()
obj()
#执行结果
sdfsdf
call

结果说明了对象名()会执行类中__call__方法
下面是wsgiref模块示例,为django框架依赖

wsgiref示例:
from wsgiref.simple_server import make_server

def run_server(environ, start_response):
    start_response('200 OK', [('Content-Type', 'text/html')])
    return [bytes('<h1>Hello, web!</h1>', encoding='utf-8'), ]

if __name__ == '__main__':
    httpd = make_server('127.0.0.1', 8000, run_server)
    httpd.serve_forever()
  1. Flask简单示例
    在使用flask之前需要进行安装,安装指令如下
pip3 install flask
from flask import Flask         #导入flask
app = Flask(__name__)      #创建app对象

@app.route('/index')
def index():
    return "Hello World"

if __name__ == '__main__':
    app.run()                        #如果启动为主函数,开启flask
#执行结果
"D:\Python 3.7.1\python.exe" "D:/BaiduYunDownload/python 学习/flask/day114课上所有/s9day114/s4.py"
 * Serving Flask app "s4" (lazy loading)
 * Environment: production
   WARNING: Do not use the development server in a production environment.
   Use a production WSGI server instead.
 * Debug mode: off
 * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)

程序已经启动,访问本地网址http://127.0.0.1:5000/index试试,发现已经可以显示出helloworld

 类似资料: