尝试在python烧瓶中的app文件夹中打开路径时找不到404?

时间:2018-04-01 07:54:40

标签: python flask

我的项目文件夹结构如下:

Project/
   app/
      templates/
        base.html
        index.html
      user/
        __init__.py
        routes.py
   venv/
   Hello.py

Hello.py是用于初始化项目的文件,因此我可以从那里打开另一条路线,以防app/user/routes.py。所以,我有Hello.py代码,如下所示:

from flask import Flask,render_template, redirect,url_for
from app import app 
from app.user.routes import *

app = Flask(__name__)

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

app/user/routes.py中我定义了一个路由函数/user,如下所示:

from flask import render_template
from app import app

@app.route('/user')
def get_user():
    user = {'username':'Migual'}
    posts = [
        {
            'author': {'username':'John'},
            'body':'Beautiful day in Portland!'
        },
        {
            'author': {'username':'Susan'},
            'body':'The Avengers movie was so cool!'
        }

    ]
    return render_template('index.html',title='Home',user=user,posts=posts);

但是,我运行$ python Hello.py,它正常工作,但在浏览器中,当我导航http://127.0.0.1:5000/user时,我得到404 Not Found,如下所示:

  

未找到在服务器上找不到请求的URL。如果你   手动输入网址,请检查拼写,然后重试。

有什么线索我如何打开/user中定义的路线routes.py?感谢。

2 个答案:

答案 0 :(得分:1)

您在app中创建了新的hello.py,并且未使用app中从app导入的app.user.routes

您的hello.py应如下所示:

from app import app 
import app.user.routes # just to define the routes

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

并且app/__init__.py应如下所示:

from flask import Flask
app = Flask(__name__)

答案 1 :(得分:0)

改变你的Hello.Py如下:

from flask import Flask,render_template, redirect,url_for
app = Flask(__name__)
from app.user.routes import *

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

将routes.py更改为:

from flask import render_template
from Hello import app

@app.route('/user')
def get_user():
    user = {'username':'Migual'}
    posts = [
        {
            'author': {'username':'John'},
            'body':'Beautiful day in Portland!'
        },
        {
            'author': {'username':'Susan'},
            'body':'The Avengers movie was so cool!'
        }

    ]
   return render_template('index.html',title='Home',user=user,posts=posts)