溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

第一個flask應用代碼詳解

發(fā)布時間:2020-06-12 04:41:12 來源:網(wǎng)絡 閱讀:3574 作者:Lovedev 欄目:開發(fā)技術

上一篇我們創(chuàng)建了第一個簡單的flask應用程序,這一篇我們來看一下,這個最簡單的應用程序都做了哪些事

  1. 第一行代碼,導入了flask類

from flask import Flask

  1. 第二步創(chuàng)建了Flask類的實例

app = Flask(__name__)

這行代碼里有一個參數(shù)name,這個參數(shù)用到告訴flask你的application的名字,官方有一句話:

If you are using a single module,name is always the correct value. If you however are using a package, it’s usually recommended to hardcode the name of your package there.

意思就是說,如果是單一的應用,用name就可以了,如果是一個應用程序包,就hardcode一個名字給這個參數(shù)。比如:
app = Flask(“myApp”)

由于目前我們的應用都相對簡單,所以統(tǒng)一使用name作為參數(shù)。

  1. 使用route()修飾器注明通過什么樣的url可以訪問我們的函數(shù),同時在函數(shù)中返回要顯示在瀏覽器中的信息
@app.route('/')
def hello_world():
    return 'Hello World!'

可以通過修改route()修飾器實現(xiàn)不同的url解析,比如,我們改成如下的樣子

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

再次運行程序,訪問/index才能顯示出hello world, 如圖所示:

  1. 最后調(diào)用run()方法,運行flask web應用程序
if __name__ == '__main__':
    app.run()

其中if name==’main’的意思是,如果此文件是直接運行的才會執(zhí)行app.run()這個方法,如果是通過import在其它py文件中調(diào)用的話是不會執(zhí)行的
比如我們修改code.py中的hello_world方法,如下:

@app.route('/index')
def hello_world():
    if __name__=='main':
        return 'Hello World!'
    else:
        return "hello my name is "+__name__

即當namemain時還是執(zhí)行原來的邏輯,返回hello world,如果不是則輸出此時的名字。

然后我們新建一個sub.py文件然后導入code.py,并且執(zhí)行hello_world方法

import Code

def CallCodeFun():
    result = Code.hello_world()
    print(result)

CallCodeFun()

執(zhí)行sub.py后,輸入結果如下:
第一個flask應用代碼詳解
此時的name是Code而不是main
而此時,在sub.py中加一句print(name)可以發(fā)現(xiàn)sub.py中的name變成了main
第一個flask應用代碼詳解
由此我們可以得出 name 如果是 main 那么代表他是一個入口文件,直接執(zhí)行的

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權內(nèi)容。

AI