Flask 简单学习一

www.python.org

http://docs.jinkan.org/docs/flask/

http://flask.pocoo.org/

用的是python3.5安装在/opt/python3这个目录下

安装了virtualven环境

新一个myproject目录,在该新建虚环境

/opt/python3/bin/virtualven --distribute venv

#virtualenv -p /usr/local/bin/python3.4 py34env


两个都可以,只有其中一个就行。

. venv/bin/activate   启动环境


启动 venv虚环境

然后

直接上代码:

#!/bin/env python
import os
from flask import Flask, request, url_for, render_template, redirect, abort, send_from_directory, make_response, session, escape
from werkzeug import secure_filename

UPLOAD_FOLDER = '/opt/myporject/upload'
ALLOWED_EXTENSIONS = set(['txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif'])

app=Flask(__name__)
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER

@app.route('/')
@app.route('/index')
def index():
    return "Flask index !!!"


@app.route('/user/<username>')
def user(username):
    return 'you name is : %s' %(username)

@app.route('/userid/<int:id>')
def userid(id):
    return 'you id is %d' %(id)

@app.route('/path/<path:path>')
def path(path):
    return 'path: %s' %(path)

@app.route('/tt/<path:p>')
def tt(p):
    if p == None:
        return 'None'
    elif p == 'a':
        return 'tt_a'
    elif p == 'b':
        return 'tt_b'
    elif p == 'cc/dd':
        return 'tt_ccdd'
    else:
        return 'other'

@app.route('/getpost', methods=['GET', 'POST'])
def getpost():
    if request.method == 'GET':
        return 'get method!'
    else:
        return 'post method!'

@app.route('/hello/')
@app.route('/hello/<name>')
def helloname(name=None):
    return render_template('hello.html', name=name)


def allowed_file(filename):
    return filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS

@app.route('/upload', methods=['GET', 'POST'])
def upload_file():
    if request.method == 'POST':
        file = request.files['file']
        if file and allowed_file(file.filename):
            filename = secure_filename(file.filename)
            file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
            return redirect(url_for('uploaded_file', filename=filename))
    return '''
    <!doctype html>
    <title>Upload new File</title>
    <h1>Upload new File</h1>
    <form action="/upload" method=post enctype=multipart/form-data>
      <p><input type=file name=file>
         <input type=submit value=Upload>
    </form>
    '''
@app.route('/uploads/<filename>')
def uploaded_file(filename):
    return send_from_directory(app.config['UPLOAD_FOLDER'], filename)


@app.route('/setcookie')
def setcookie():
    resp = make_response("setcookie!!!!!!!!!")
    resp.set_cookie('username','theusername')
    return resp

@app.route('/getcookie')
def getcookie():
    u = request.cookies.get('username')
    return u

@app.route('/sessionindex')
def sessionindex():
    if 'username' in session:
        return 'Logged in as %s' % escape(session['username'])
    return 'You are not logged in'

@app.route('/sessionlogin', methods=['GET', 'POST'])
def sessionlogin():
    if request.method == 'POST':
        session['username'] = request.form['username']
        return redirect(url_for('sessionindex'))
    return '''
        <form action="" method="post">
            <p><input type=text name=username>
            <p><input type=submit value=Login>
        </form>
    '''

@app.route('/sessionlogout')
def logout():
    # remove the username from the session if it's there
    session.pop('username', None)
    return redirect(url_for('sessionindex'))

# set the secret key.  keep this really secret:
app.secret_key = 'A0Zr98j/3yX R~XHH!jmN]LWX/,?RT'


@app.route('/testlogdebug')
def testlogdebug():
    app.logger.debug('debug logger')
    return 'debug logger'

@app.route('/testlogwarning')
def testlogwarning():
    app.logger.warning('warning logger')
    return 'warning logger'

@app.route('/testlogerror')
def testlogerror():
    app.logger.error('error logger')
    return 'error logger'

if __name__ == '__main__':
    app.run(host='0.0.0.0', debug=True)


测试结果就不写了。 按照官访来的。




你可能感兴趣的:(Flask 简单学习一)