Flask
虚拟环境的配置
pip install virtualenv
创建一个虚拟环境,参数是虚拟环境的目标目录
virtualenv venv
激活虚拟环境
source venv/bin/activate
运行所需的依赖包
pip freeze > requirements.txt
1 开启调试模式,修改代码后不需要手动重启
app = Flask(__name__) app.debug = True
2 路由中的变量
@app.route('/<name>', methods=['GET', 'POST']) def home(name): return render_template('home.html',name=name)
3 关于配置文件
PASSWORD = '123456' app = Flask(__name__) app.debug = True app.config.from_object(__name__) print app.config['PASSWORD']
4 关于前端页面发送消息至后端
第一种: ajax
前端: $.post('/test',{ a:"data1", b:"data2" }, function(data,status){ alert("数据" + data + "状态" + status)
如果返回的json格式,则 JSON.parse(data).name })
后端:
a = request.form["a"]
b = request.form["b"]
print a + b
return "hello"
也可以 返回 dit
import json
from flask import, jsonify
c = {"name":"jinkang","sex":"man"}
return json.dumps(c)
第二种 就是 form 提交表单
<form action="/" method="post">
后端 request.form["name"] 获取 <input name="name" value="value">的值。
建议循环 request.form
for x,y in dic.iteritems():
x y 循环 表单中的 name 和 value 值。
错误页面的自定义
@app.errorhandler(404) def not_find(error): return "404"
一个 session 和 flash 消息的例子
# -*- coding: utf-8 -*- from flask import Flask, request, render_template, jsonify,redirect, url_for,session,escape,flash import os,commands import json from werkzeug import secure_filename app = Flask(__name__) app.debug = True app.secret_key = "adsfadfad" @app.route('/', methods=['GET', 'POST']) def index(): return render_template('home.html') @app.route('/login', methods=['POST','GET']) def login(): username = request.form['username'] password = request.form['password'] if(username == "admin" and password == "123456"): session['username'] = username return redirect(url_for('homepage')) else: flash("the wrong username and password",'error'); return render_template('home.html') @app.route('/homepage', methods=['POST','GET']) def homepage(): if('username' in session): return "welcome" + session['username'] else: return render_template('home.html') @app.errorhandler(404) def not_find(error): return "404" if __name__ == '__main__': app.run(host='0.0.0.0',port=3999)
关于模板继承
模板
<div> <h1 style="color: red">THIS IS A TITLE</h1> </div> {% block content %}{% endblock %}
继承
{% extends "base.html" %} {% block content %} 888888 {% endblock %}
关于 FLASK-RESTful 的一个例子
from flask import Flask,request from flask.ext import restful app = Flask(__name__) api = restful.Api(app) class HelloWorld(restful.Resource): def get(self): return {'id': 'getmethod'} def post(self): val = request.form['key'] print val return {'id': val} api.add_resource(HelloWorld, '/hello') if __name__ == '__main__': app.run(debug=True,port=3999)