Python 如何在烧瓶中生成动态网址?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/35107885/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 16:00:10  来源:igfitidea点击:

How to generate dynamic urls in flask?

pythonflask

提问by I Love Python

I have several records in the database which I Want to form URLs like so:

我在数据库中有几条记录,我想像这样形成 URL:

mysite.com/post/todays-post-will-be-about

mysite.com/post/todays-post-will-be-about

The todays-post-will-be-aboutwill be pulled from a Database.

todays-post-will-be-about会从数据库中拉出。

Is there some way I could pull this off in flask?

有什么办法可以把它放在烧瓶里吗?

采纳答案by ATLUS

You can put variable names in your views.py functions. For example:

您可以在 views.py 函数中放置变量名称。例如:

# you can also use a particular data type such as int,str
# @app.route('post/<int:id>', methods=['GET', 'POST'])
@app.route('post/<variable>', methods=['GET'])
def daily_post(variable):
    #do your code here
    return render_template("template.html",para1=meter1, para2=meter2)

To get your database information to display on your site, you'll want to pass parameters into the template. So, in your template you'll reference those parameters like:

为了让您的数据库信息显示在您的站点上,您需要将参数传递到模板中。因此,在您的模板中,您将引用这些参数,例如:

<td>Post Author: {{ para1.author }}</td>
<td>Post Body: {{ para1.body }}</td>
<td>Date Posted: [{{ para2 }}] times</td>

Then when you visit mysite.com/post/anything_here, the 'anything_here' will go into your function and be evaluated as necessary. You'll probably also want to set up 404 page handling, in case someone tries to enter a post manually:

然后,当您访问 mysite.com/post/anything_here 时,“anything_here”将进入您的函数并根据需要进行评估。您可能还想设置 404 页面处理,以防有人尝试手动输入帖子:

@app.errorhandler(404)
def not_found_error(error):
    return render_template('404.html', pic=pic), 404

回答by Wombatz

Flask routes can have parameters as shown here:

瓶路线可以有参数显示在这里

@app.route("post/<identifier>")
def post(identifier):  # parameter name must match dynamic route parameter name
    the_post = get_from_database_by(identifier)
    response = make_response_from_entity(the_post)
    return response

How you get the post from the database and how you make a response from that is up to you.

您如何从数据库中获取帖子以及如何从中做出回应取决于您。

回答by sisanared

Use the @app.routedecorator like shown below:

使用@app.route如下所示的装饰器:

@app.route('/post/<post_title>')
def show_post(post_title):
    #use post title to fetch the record from db

More examples are available under the Routing section: http://flask.pocoo.org/docs/0.10/quickstart/#routing

路由部分提供了更多示例:http: //flask.pocoo.org/docs/0.10/quickstart/#routing

回答by Ritero

I suggest SQLAlchemy http://flask-sqlalchemy.pocoo.org/It is a very simple and quick way

我建议使用 SQLAlchemy http://flask-sqlalchemy.pocoo.org/这是一个非常简单快捷的方法

app.py

应用程序

from flask import Flask, render_template

try:
    from .alchemy import Post, db

except:
    from alchemy import Post, db

app = Flask(__name__)

@app.route('/post/<url>')
def post(url):
    url = Post.query.filter_by(url=url).first_or_404()
    id = url.id
    author = url.author 
    title = url.title
    body = url.body
    date = url.date
    return render_template('post.html', title=title, id=id, author=author, body=body, date=date)

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

alchemy.py

炼金术.py

from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy
import datetime

app = Flask(__name__)
SQLALCHEMY_TRACK_MODIFICATIONS = True
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://root:pasword@localhost/base'
db = SQLAlchemy(app)


class Post(db.Model):
    __tablename__ = "table"
    id = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.String(200))
    url = db.Column(db.String(220))
    author= db.Column(db.String(50))
    body = db.Column(db.String(50000))
    date  = db.Column(db.DateTime)

    def __init__(self, title, url, author, body):
        self.title = title
        self.url = url 
        self.author= author
        self.body = body 
        self.date = datetime.datetime.utcnow()

    def __repr__(self):
        return '<Post %r>' % self.url