目录Django VS Flask VS Tornado
Django
Flask
Tornado
1.Django VS Flask VS Tornado
对比项目:url配置
静态文件+模板的配置
报错页面的处理
Templates 中模板标签 (插值 /控制语句/Escape/加载静态/自定义模板库)
部署运行方式
2.Django
(1)代码
# url配置
path('', views.index)
path('dir/', views.xx)
re_path(r'article/(?P\d+)/$', views.article)
# Database
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
},
# 'default': {
# 'ENGINE': 'django.db.backends.mysql',
# 'HOST': '127.0.0.1',
# 'PORT': 3306,
# 'NAME': 'djangodb',
# 'USER': '',
# 'PASSWORD': '',
# }
}
# 静态文件+模板
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': ['Blog/templates'],
'APP_DIRS': True,
'OPTIONS': {'context_processors': [],},
},
]
STATIC_URL = '/static/'
if not DEBUG:
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
else:
STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')]
if not settings.DEBUG:
urlpatterns += [re_path(r'^static/(?P.*)$', static.serve, {'document_root': settings.STATIC_ROOT}),]
# Views中render
def xx(request):
if request.method == "GET":
return render(request, 'xx.html',{'abc': 11})
elif request.method == "POST":
return render(request, 'xx.html',{'abc': 22})
# 报错界面
直接在templates目录下放错误状态码对应的html文件,如404.html
# Templates 中模板标签
## 插值
{{ xx }}
## 控制语句
{% if %}{% else %}{% endif %}
{%for x in xx reversed %}{%endfor%}
## 加载静态
{% load static %}
{% static 'xx.png' %}
## 过滤器
{{ xx | upper }}
{{ xx | lower }}
{{ xx | capfirst }}
## 自定义模板库
{% extends "xx.html" %}
{% block yy %}{% endblock %}
(2)Admin后台
(3)缓存优化类型:memcached/数据库/文件系统/local-memory/dummy/custom
粒度:全网站/view/模板片段/low-level
优化性能评估:合适的粒度/cached_property/惰性机制/数据库优化(优化文档/持久连接)
(4)项目部署
先设置出错模板/设置缓存memcache/设置数据库mysql
部署方式:本机部署
Django+mod wsgi+Apache(适合小型网站)
Django+Gunicorn+nginx
(5)框架使用步骤
let '...\site-packages\django\bin' joined system path
above project path> django-admin startproject xxProject
above project path> cd xxproject
project path> django-admin startapp xxSite
create new folder: templates in xxSite
(6)本地运行
project path> python manage.py runserver
project path> python manage.py migrate
project path> python manage.py createsuperuser
project path> python manage.py runserver
3.Flask
(1)代码
# Database
dbinfo = {
'ENGINE': 'mysql',
'DRIVER': 'pymysql',
'DB_NAME': '',
'USER': '',
'PASSWORD': '',
'HOST': '127.0.0.1',
'PORT': 3306,
}
# 静态文件+模板
app = Flask(__name__, static_folder='static')
# Views中render + url配置
## 蓝图
blue = Blueprint('blue', __name__)
def init_blue(app):
app.register_blueprint(blue)
## url处理
@app.route('/abc/?key=value', methods=['GET', 'POST'])
或@app.route('/xxx/')
或@app.route('/path/')
def index():
if request.method == 'POST':
x = request.args.get('key', '')
return render_template('xx.html', x=x)
# 报错界面
@app.errorhandler(404)
def page_not_found(error):
# use template
# return render_template('page_not_found.html'), 404
# gain response and change
resp = make_response(render_template('error.html'), 404)
resp.headers['X-Something'] = 'A value'
return resp
# Templates 中模板标签
## 插值
{{x}}
{# xxx #}
{{x.val}} or {{x[val]}}
## 控制语句
{% if xx %} {% else %} {% endif %}
{% for x in xx %} {% endfor %}
{% for m in get_flashed_messages() %} {% endfor%}
## 加载静态
{{url_for('static', filename='css/style.css')}}
## Escape
{{var| filtername(*args)}}
## 过滤器
{{'%s is %d' | format('xx',7)}}
{{x | reverse | upper}}
## 自定义模板库
{% extends 'xx.html' %}
{% block title %}{% endblock %}
(2)本地运行
Method 1) path> set FLASK_APP=manage.py
path> flask run
Method 2) path> python -m flask run
Method 3) path>python -m flask run --host=0.0.0.0 (all users)
(3)部署运行
Gunicorn Common 1) gunicorn -w 4 -b 127.0.0.1:4000 myproject:app
Gunicorn Factory 2) gunicorn "myproject:create_app()"
uWSGI 1) uwsgi --http 127.0.0.1:5000 --module myproject:app
twistd 1) twistd -n web --port tcp:8080 --wsgi myproject.app
Gevent 1) python manage_gevent.py
4.Tornado
(1)代码
# url配置
(r'/', IndexHandler)
(r'.*', ErrorHandler)
# Database
self.conn = pymysql.Connection(host='', password='', database='', user='', port='')
self.cursor = self.conn.cursor()
# 静态文件+模板
template_path=os.path.join(os.path.dirname(os.path.abspath(__file__)), 'templates')
static_path=os.path.join(os.path.dirname(os.path.abspath(__file__)), 'static')
# Views中render
class MainHandler(web.RequestHandler):
# get/post/delete/patch/put
def get(self):
self.render('xx.html', items=items)
# receive values
# GET/POST: self.get_argument()/ self.get_arguments()
# GET: self.get_query_argument()/ self.get_query_arguments()
# POST: self.get_body_argument()/ self.get_body_arguments()
# 报错页面
class ErrorHandler(web.RequestHandler):
def get(self):
self.write_error(404)
def write_error(self, status_code, **kwargs):
if status_code == 404:
self.write('404')
# Templates 中模板标签
## 插值
{{items}}
{{items[0]}}
{# comments #}
{% set x=1 %}
## 控制语句
{%for x in xx %}{{ a }}{% continue %}{% break %}{%end%}
{% if a=='xx'%}{% elif a=='yy' %}{% else %}{% end %}
{% while xx %}{% end %}
{% try %}{% except %}{% finally %}{% end %}
{% module xx() %}
{% apply function %}{% end %}
## Escape
{% autoescape function %}
{% autoescape None %}
{% raw xx %}
## 加载静态
{{ static_url('xx.png')}}
## 自定义模板库
{% extends 'xx.html' %}
{% block title %}{% end %}
(2)运行
project path > python manage.py (default port:8000)