33

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

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

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

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

Ben Morris
  • 606
  • 5
  • 24
I Love Python
  • 862
  • 2
  • 13
  • 20
  • So the URL for the day specific page changes every day depending on the URL returned by the database? It's not like `/post/today` is constant, but directing to different URLs each day? – albert Jan 30 '16 at 22:24

4 Answers4

43

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

# 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:

@app.errorhandler(404)
def not_found_error(error):
    return render_template('404.html', pic=pic), 404
Smit Mehta
  • 91
  • 9
ATLUS
  • 836
  • 6
  • 8
  • I haven't actually given much thought into Flask SEO (Search Engine Optimization), because I am working on a church website as a side project. However, if I understand SEO correctly, crawlers click through your website and index those pages so as long as all the dynamic URLs are in clickable distance you don't need any special optimizations – ATLUS Jan 30 '16 at 22:34
  • @ILovePython If google can click the link, they'll be able to crawl. Crawlers work by clicking links and indexing the page they get to, so as long as it's clickable they'll be able to crawl the URLs. – ATLUS Jun 01 '17 at 16:01
14

Use the @app.route decorator like shown below:

@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

sisanared
  • 4,175
  • 2
  • 27
  • 42
8

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.

Wombatz
  • 4,958
  • 1
  • 26
  • 35
0

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

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

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
Ritero
  • 80
  • 8