python flask 試用

1、安裝flaskflask

    官方文檔:http://docs.jinkan.org/docs/flask/session

    我是使用pip安裝,安裝好之後須要經過import使用app

 

2、熟悉的hello world,上代碼,url

from flask import Flask


app = Flask(__name__)
app.debug = True


@app.route('/')
def index():
    return 'Hello World'

if __name__ == '__main__':
    app.run()

    說明:第一行是引用flask,debug

 

3、地址跳轉,上代碼,ip

from flask import Flask,session, redirect, url_for


app = Flask(__name__)
app.debug = True


@app.route('/')
def index():
    if 'username' in session:
        return 'Logged in as %s'
    else:
        return redirect(url_for('login'))

@app.route('/hello')
def hello():
    return 'Hello World'

@app.route('/login')
def login():
    return 'You are not logged in'


if __name__ == '__main__':
    app.run()

    說明:index方法會進行判斷是否有用戶登錄,沒有會跳轉到login登錄,跳轉地址前要加return,否則報錯文檔

 

4、引用其餘類方法,上代碼pip

from flask import Flask,session, redirect, url_for

import test

app = Flask(__name__)
app.debug = True

@app.route('/myword')
def myword():
    ww = test.myWord()
    return ww

@app.route('/')
def index():
    if 'username' in session:
        return 'Logged in as %s'
    else:
        return redirect(url_for('login'))

@app.route('/hello')
def hello():
    return 'Hello World'

@app.route('/login')
def login():
    return 'You are not logged in'


if __name__ == '__main__':
    app.run()

    說明:經過import引用其餘類,而後把對應方法所返回的內容經過return 輸出,否則會報錯io

相關文章
相關標籤/搜索