安装:pip install flask
Flask有两个依赖:1,路由,调试和wsgi。2,Jinja2模板系统。
所有的Flask程序都必须创建一个程序实例,web服务器使用一种名为wsgi的协议,把接受自客户端的所有请求都转交给这个对象处理。程序实例搜索Flask类的对象。Flask类的构造函数只有一个必须要指定的参数。
客户端把请求发送给web服务器,web服务器再把请求发送给Flask程序实例。程序实例需要知道对每个URL请求运行哪些代码,所以保存了一个URL到python函数的映射关系。处理URL和函数之间关系的程序称为路由。
#!/usr/bin/env python # -*- coding: UTF-8 -*- from flask import Flask,render_template,request,redirect #实例化Flask对象,模板默认是templates文件夹,flask静态文件的位置是static, #static_url_path='static'指定前端静态的名字 app = Flask('xxx',template_folder="templates",static_folder="static",static_url_path='static') ''' 1,先执行app.route('/index'),并且返回xx 2,@xx def index(): return "Hello World" 3,执行index = xx(index) 本质{ '/index':index } ''' #默认只支持get方法提交 @app.route("/index",methods=['GET','POST']) def login(): #flask获取前端传值用request if request.method == "GET": return render_template("login.html") else: user = request.form.get('info')#login.html中对应的值 pwd = request.form.get('pwd') if user == "name" and pwd == "password" return redirect("")#登录成功以后跳转的函数 if __name__ == '__main__': app.run() ''' 执行app.run()方法以后 以后会跳转到run_simple(host, port, self, **options)方法 最后执行call方法。 为flask框架的入口 def __call__(self, environ, start_response): """Shortcut for :attr:`wsgi_app`.""" return self.wsgi_app(environ, start_response) '''
#配置模板,静态文件位置 app = Flask('xxxx',template_folder="templates") #配置secret app.secret_key = 'as9231rjksakdj28222' #配置文件参数 app.config可以指定要配置的参数 #导入配置文件下面的类,根据字符串自动找到类下面的方法去运行 app.config.from_object('setings.Testingconfig')