python flask 试用

  • Post author:
  • Post category:python


一、安装flask

官方文档:http://docs.jinkan.org/docs/flask/

我是使用pip安装,安装好以后需要通过import使用

二、熟悉的hello world,上代码,

from flask import Flask


app = Flask(__name__)
app.debug = True


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

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

说明:第一行是引用flask,

三、地址跳转,上代码,

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,不然报错

四、引用其他类方法,上代码

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 输出,不然会报错

转载于:https://my.oschina.net/u/3268486/blog/3101214