python框架-Flask初探

1、安装

pip3 install flask 

2、特点

  • 短小精悍、可扩展强 的一个Web框架。

    • 注意:上下文管理机制
  • 依赖wsgi:werkzurg

  • werkzurg:
    示例一:

				from werkzeug.wrappers import Request, Response
				from werkzeug.serving import run_simple

				def run(environ,start_response):

					return [b"asdfasdf"]

				if __name__ == '__main__':

					run_simple('localhost', 4000, run)
					

示例二:

	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)
from flask import Flask
app = Flask(__name__)
@app.route('/index')
def index():
	return "Hello World"
if __name__='__main__':
	app.run()

3. 配置文件

app.config.from_object("settings.DevelopmentConfig")
		
		
		class Config(object):
			DEBUG = False
			TESTING = False
			DATABASE_URI = 'sqlite://:memory:'


		class ProductionConfig(Config):
			DATABASE_URI = 'mysql://user@localhost/foo'


		class DevelopmentConfig(Config):
			DEBUG = True


		class TestingConfig(Config):
			TESTING = True

4. 路由系统

  • endpoint,反向生成URL,默认函数名
  • url_for(‘endpoint’) / url_for(“index”,nid=777)
  • 动态路由:
			@app.route('/index/',methods=['GET','POST'])
			def index(nid):
				print(nid)
				return "Index"
		

6. 请求相关

		# 请求相关信息
		# request.method
		# request.args
		# request.form
		# request.values
		# request.cookies
		# request.headers
		# request.path
		# request.full_path
		# request.script_root
		# request.url
		# request.base_url
		# request.url_root
		# request.host_url
		# request.host
		# request.files
		# obj = request.files['the_file_name']
		# obj.save('/var/www/uploads/' + secure_filename(f.filename))

7. 响应:

	响应体:
	return “asdf”
	return jsonify({'k1':'v1'})
	return render_template('xxx.html')
	return redirect()		
	定制响应头:   
	obj = make_response("asdf")
	obj.headers['xxxxxxx'] = '123'
	obj.set_cookie('key', 'value')
	return obj
render_template('index.html',stu_dic=STUDENT_DICT)
		版本二:
		import functools
		def auth(func):
			@functools.wraps(func)
			def inner(*args,**kwargs):
				if not session.get('user'):
					return redirect(url_for('login'))
				ret = func(*args,**kwargs)
				return ret
			return inner
		
		@app.route('/index')
		@auth
		def index():
			return render_template('index.html',stu_dic=STUDENT_DICT)
		
应用场景:比较少的函数中需要额外添加功能。
			版本三:before_request
			@app.before_request
			def xxxxxx():
				if request.path == '/login':
					return None

				if session.get('user'):
					return None

				return redirect('/login')

7. 模板渲染

  • 基本数据类型:可以执行python语法,如:dict.get() list[‘xx’]
  • 传入函数
  • django,自动执行
  • flask,不自动执行
  • 全局定义函数
			@app.template_global()
			def sb(a1, a2):
				# {{sb(1,9)}}
				return a1 + a2

			@app.template_filter()
			def db(a1, a2, a3):
				# {{ 1|db(2,3) }}
				return a1 + a2 + a3
  • 模板继承layout.html
				
				
				
					
					Title
					
				
				
					

模板

{% block content %}{% endblock %} tpl.html {% extends "layout.html"%} {% block content %} {{users.0}} {% endblock %} - include {% include "form.html" %} form.html
asdfasdf asdfasdf asdf asdf
- 宏 {% macro ccccc(name, type='text', value='') %}

{% endmacro %} {{ ccccc('n1') }} {{ ccccc('n2') }}
  • 安全
    • 前端: {{u|safe}}
    • 前端: MarkUp(“asdf”)

8. session

当请求刚到来:flask读取cookie中session对应的值:eyJrMiI6NDU2LCJ1c2VyIjoib2xkYm95,将该值解密并反序列化成字典,放入内存以便视图函数使用。
视图函数:

			@app.route('/ses')
			def ses():
				session['k1'] = 123
				session['k2'] = 456
				del session['k1']

				return "Session"

					
						
					session['xxx'] = 123
					session['xxx']

当请求结束时,flask会读取内存中字典的值,进行序列化+加密,写入到用户cookie中。

9. 闪现,在session中存储一个数据,读取时通过pop将数据移除。

		from flask import Flask,flash,get_flashed_messages
		@app.route('/page1')
		def page1():

			flash('临时数据存储','error')
			flash('sdfsdf234234','error')
			flash('adasdfasdf','info')

			return "Session"

		@app.route('/page2')
		def page2():
			print(get_flashed_messages(category_filter=['error']))
			return "Session"

10. 中间件

  • call方法什么时候出发?
  • 用户发起请求时,才执行。
  • 任务:在执行call方法之前,做一个操作,call方法执行之后做一个操作。
			class Middleware(object):
				def __init__(self,old):
					self.old = old

				def __call__(self, *args, **kwargs):
					ret = self.old(*args, **kwargs)
					return ret


			if __name__ == '__main__':
				app.wsgi_app = Middleware(app.wsgi_app)
				app.run()

11. 特殊装饰器

1. before_request
		
		2. after_request
		
			示例:
				from flask import Flask
				app = Flask(__name__)


				@app.before_request
				def x1():
					print('before:x1')
					return '滚'

				@app.before_request
				def xx1():
					print('before:xx1')


				@app.after_request
				def x2(response):
					print('after:x2')
					return response

				@app.after_request
				def xx2(response):
					print('after:xx2')
					return response



				@app.route('/index')
				def index():
					print('index')
					return "Index"


				@app.route('/order')
				def order():
					print('order')
					return "order"


				if __name__ == '__main__':

					app.run()
		
		3. before_first_request
		
			from flask import Flask
			app = Flask(__name__)

			@app.before_first_request
			def x1():
				print('123123')


			@app.route('/index')
			def index():
				print('index')
				return "Index"


			@app.route('/order')
			def order():
				print('order')
				return "order"


			if __name__ == '__main__':

				app.run()

		
		4. template_global
		
		5. template_filter
		
		6. errorhandler
			@app.errorhandler(404)
			def not_found(arg):
				print(arg)
				return "没找到"

你可能感兴趣的:(Python,框架,Flask,Python面试笔记)