flask学习记录尽量将学习的部分写到了一个文件中。
数据库交互部分还是用python-mysql。
主要是学习,不考虑交互,大并发部分。
详细结构在附件中。
#!/bin/env python # -*- coding:utf-8 -*- # Date: 2015-04-01 # Author: simonzhang # web: www.simonzhang.net # Email: simon-zzm@163.com # _ooOoo_ # o8888888o # 88" . "88 # (| -_- |) # O\ = /O # ____/`---'\____ # .' \\| |// `. # / \\||| : |||// \ # / _||||| -:- |||||- \ # | | \\\ - /// | | # | \_| ''\---/'' | | # \ .-\__ `-` ___/-. / # ___`. .' /--.--\ `. . __ # ."" '< `.___\_<|>_/___.' >'"". # | | : `- `.;`\ _ /`;.`/ - ` : | | # \ \ `-. \_ __\ /__ _/ .-` / / #======`-.____`-.___\_____/___.-`____.-'====== # `=---=' #^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ # 佛祖保佑 代码高性能 不宕机 无bug ### END INIT INFO import os from flask import Flask, url_for from flask import request, render_template, redirect from flask import session, escape # 上传使用 from werkzeug import secure_filename # 导入配置文件 from config import * # 还是使用python mysql获取数据 from mysqlrun import * app = Flask(__name__) # 过滤后缀 def allowed_file(filename): return '.' in filename and \ filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS # 测试GET和POST,文件上传部分 # 测试GET的链接 http://127.0.0.1:5000/test?name=simonzhang.net @app.route('/test', methods=['GET', 'POST']) def test(name=None): if request.method == 'GET': if request.args.get('name',''): _name = request.args.get('name','') else: _name = 'hi' return render_template('test.html', name=_name) elif request.method == 'POST': file = request.files['upfile'] # 上传了真实文件,并且后缀是通过的才保存 if file and allowed_file(file.filename): # 此部分需要使用 from werkzeug import secure_filename file.save(os.path.join(app.config['UPLOAD_FOLDER'], secure_filename(file.filename))) return render_template('test.html', name="ok") else: pass # 测试cookie 当前还未完全成功 from flask import make_response @app.route('/testcookie', methods=['GET']) def testcookie(): if request.method == 'GET': get_type = request.args.get('t','') get_value = request.args.get('v','') if get_type == 'r': _v = request.cookies.get('username') return 'user name : %s' % _v else: #resp = make_response(render_template('/')) request.set_cookie('username', get_value) return 'ok !!@' # 错误页 @app.errorhandler(404) def page_not_found(error): return render_template('404.html'), 404 # 判断是否登陆 @app.route('/') def index(): if 'username' in session: return 'Logged in as %s' % escape(session['username']) return 'You are not logged in' # 登陆,简单的登陆页面,使用session @app.route('/login', methods=['GET', 'POST']) def login(): if request.method == 'POST': session['username'] = request.form['username'] return redirect(url_for('index')) return '''''' # 注销 @app.route('/logout') def logout(): session.pop('username', None) return redirect(url_for('index')) if __name__ == '__main__': #app.debug = False app.debug = True # 上传部分 app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER app.config['MAX_CONTENT_LENGTH'] = UPLOAD_FILE_SIZE # 安全 app.secret_key = secret_key app.run(host = '0.0.0.0', port=500)
发表评论