gpt4 book ai didi

python - 在 linux 中运行 flask/python 代码?基本 flask 代码

转载 作者:太空狗 更新时间:2023-10-29 12:18:19 31 4
gpt4 key购买 nike

我一直在通过本教程学习 flask/python http://blog.miguelgrinberg.com/post/the-flask-mega-tutorial-part-i-hello-world

这个博客很不错,解释的也很好。在第一个教程中,如果您注意到,他要求我们创建一个 init.py 文件、一个 views.py 文件和一个 main run.py 文件。

root
/microblog
/apps
/__init__.py
views.py

我创建了这两个文件。他要求我们创建一个 run.py 文件并将其放在根文件中。然后

chmod a+x run.py
./run.py

它说文件不存在。如果我,

python run.py

它说 App 模块未定义。我无法找出问题所在,我将 run.py 文件放入所有文件中,但它始终无法正常工作。

我还将包含代码,这样可以更轻松地回答而不是转到上面的链接

初始化.py

from flask import Flask
app = Flask(__name__)
from app import views

View .py

from app import app
@app.route('/')
@app.route('/index')
def index():
return 'Hello world'

运行.py

#!flask/bin/python
from app import app
app.run(debug = True)

我的问题:

  1. 我应该把 run.py 文件放在哪里?

  2. 为什么我们要创建不同的文件?为什么不能全部合而为一完整文件?

    初始化.py -->

    • 他正在进口 flask ,这很正常。然后分配 app =(姓名)。这是为什么?那他为什么要从应用程序中导入 View ?

View .py -->

  1. 从应用导入应用?应用程序是这里的现有模块还是我们的模块刚刚创建? @app.route('/')
    是什么@app.route('/index')做什么?

谁能把代码放在一起解释一下?

最佳答案

It says App module not defined

你拼错了包名:你的目录树中有应用程序,你尝试导入应用程序

Where should I put the run.py file?

只要应用程序在 PYTHONPATH 中,您想要的任何地方。或者放在微博目录下。

he is importing flask which is normal. then assigning app = (name). why is that?

# Create reference to flask WSGI application object
app = Flask(__name__)

为什么?因为您需要应用程序才能运行。参见官方文档: Flask object

Then why is he importing views from apps?

from app import views

意思是:从名为app的包导入名为views的模块

命名约定可能会有所不同,但如果您没有看到差异,您可能应该在开始更复杂的东西之前花更多的时间学习 python 基础知识。

from app import app? is app an existing module here or the one we just created? what > does @app.route('/') or @app.route('/index')do?

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

简答:如果应用收到 url '/' 的请求,则使用函数 foo 进行响应有关更多信息,请参阅官方文档:add_url_ruleURL Route Registrations

更新

Why are we creating different files? Why cant all of them be in one full file?

实际上,没有什么可以阻止您将所有内容都放在一个文件中,但大多数时候这确实是个坏主意。如果您询问这个特定示例中的推理,它主要是关于分离具有不同职责的模块。

关于python - 在 linux 中运行 flask/python 代码?基本 flask 代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18684055/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com