Flask 簡單學習一

www.python.orghtml

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

http://flask.pocoo.org/flask

用的是python3.5安裝在/opt/python3這個目錄下bash

wget https://www.python.org/ftp/python/3.6.3/Python-3.6.3.tgz
tar -xvzf Python-3.6.3.tgz
./configure --prefix=/opt/python3
make
make install

cd /opt/python3/
./bin/pip3 install virtualenv

 

mkdir ~/mypythondir/pythonproject1 -p
cd ~/mypythondir/pythonproject1
/opt/python3/bin/virtualenv --distribute venv
#virtualenv 生成一個名爲venv的虛擬python環境,通常項目的虛擬環境都放在項目文件夾內部
. venv/bin/activate
#激活虛擬環境

mkdir ~/mypythondir/pythonproject2 -p
cd ~/mypythondir/pythonproject2
/opt/python3/bin/python3 -m venv .
#使用python3自帶得venv模塊生成一個python環境,最後的那個點爲路徑,通常項目的虛擬環境都放在項目文件夾內部
source bin/activate
#激活虛擬環境

安裝了virtualven環境cookie

新一個myproject目錄,在該新建虛環境session

 

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

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

 

兩個均可以,只有其中一個就行。app

 

. venv/bin/activate   啓動環境

 

 

 

啓動 venv虛環境post

而後測試

直接上代碼:this

 

#!/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)

 

 

 

測試結果就不寫了。 按照官訪來的。

相關文章
相關標籤/搜索