Home  >  Q&A  >  body text

python - Query data with flask+sqlalchemy

After I log in and it is included in the main page, will the data on the main page be received using the form? I don’t know how to put the found data on the page. Is there any information you can recommend or some guidance?

怪我咯怪我咯2711 days ago894

reply all(3)I'll reply

  • 大家讲道理

    大家讲道理2017-05-18 11:01:39

    I want to display the data found from the database on the page. I want to know if it is submitted using a form? No reference found

    I will answer the original poster’s question based on this sentence.

    Let me summarize the idea first: use routing to pass the data queried by SQLAlchemy to the render_template function through parameters, and then use jinja2 in the .html file to dynamically render the web page.

    For example, now you have a blog database and you need to display the blog content on the homepage. How to display it?

    The main method is actually defined in jinja2来实现,首先假设你有一个Post数据库(已经在models.py, don’t tell me you don’t understand! ! )

    Well you don’t understand, it’s like this:

    from . import db
    
    class Post(db.Model):
        __tablename__ = 'posts'
        id = db.Column(db.Integer, primary_key=True)
        body = db.Column(db.Text)
        body_html = db.Column(db.Text)
        timestamp = db.Column(db.DateTime, index=True, default=datetime.utcnow)
        author_id = db.Column(db.Integer, db.ForeignKey('users.id'))
        comments = db.relationship('Comment', backref='post', lazy='dynamic')
        
    db.event.listen(Post.body, 'set', Post.on_changed_body)

    Why don’t you understand where db import comes from? It’s from the app package __init__.py! I’m too lazy to explain it here, so I’ll just post the complete init method

    from flask import Flask
    from flask_bootstrap import Bootstrap
    from flask_mail import Mail
    from flask_moment import Moment
    from flask_sqlalchemy import SQLAlchemy
    from flask_login import LoginManager
    from flask_pagedown import PageDown
    from config import config
    
    bootstrap = Bootstrap()
    mail = Mail()
    moment = Moment()
    db = SQLAlchemy()
    pagedown = PageDown()
    
    login_manager = LoginManager()
    login_manager.session_protection = 'strong'
    login_manager.login_view = 'auth.login'
    
    
    def create_app(config_name):
        app = Flask(__name__)
        app.config.from_object(config[config_name])
        config[config_name].init_app(app)
    
        bootstrap.init_app(app)
        mail.init_app(app)
        moment.init_app(app)
        db.init_app(app)
        login_manager.init_app(app)
        pagedown.init_app(app)
    
        if not app.debug and not app.testing and not app.config['SSL_DISABLE']:
            from flask_sslify import SSLify
            sslify = SSLify(app)
    
        from .main import main as main_blueprint
        app.register_blueprint(main_blueprint)
    
        from .auth import auth as auth_blueprint
        app.register_blueprint(auth_blueprint, url_prefix='/auth')
    
        from .api_1_0 import api as api_1_0_blueprint
        app.register_blueprint(api_1_0_blueprint, url_prefix='/api/v1.0')
    
        return app
    
    

    But before changing the database, remember to run python manager.py shell to migrate the database first (check it yourself for details)
    I’m going too far, let’s look at the original poster’s problem.

    First let’s look at the content in routing (that’s views.py):

    @main.route('/', methods=['GET', 'POST'])
    def index():
        #前面已经假设了你有个Post数据库
        query = Post.query
        #这里使用了pagination,就是自动实现翻页的一个扩展,可用可不用哈
        pagination = query.order_by(Post.timestamp.desc()).paginate(
            page, per_page=current_app.config['FLASKY_POSTS_PER_PAGE'],
            error_out=False)
        #这里才是重点,简单来说就是让posts=Post.query.order_by(Post.timestamp.desc())
        posts = pagination.items
        #然后用render_template传给html,交给jinja2来动态渲染
        return render_template('index.html', form=form, posts=posts,
                               show_followed=show_followed, pagination=pagination)
    

    Now let’s go to index.html to see how jinja2 works. But in order to make index.html look as simple as possible, I The module for printing Post is proposed separately and is called _post.html. To use it in index.html, just {% include '_posts.html' %}< /code>That’s it: index.html中来看看jinja2该如何工作,不过为了让index.html看上去尽量简洁,我将打印Post的模块单独提了出来,叫_post.html,在index.html中使用只要{% include '_posts.html' %}即可:
    让我们来看_post.htmlLet’s take a look at _post.html

    <ul class="posts">
        <!--处理从路由传进来的posts,用一个for循环处理,语法酷似python-->
        {% for post in posts %}
        <li class="post">
            <p class="post-thumbnail">
                <a href="{{ url_for('.user', username=post.author.username) }}">
                    <img class="img-rounded profile-thumbnail" src="{{ post.author.gravatar(size=40) }}">
                </a>
            </p>
            <p class="post-content">
            
                <!--Post数据在这里显示,你要的答案就在这了。核心思想就是用jinja2 -->
                <p class="post-date">{{ moment(post.timestamp).fromNow() }}</p>
                <p class="post-author"><a href="{{ url_for('.user', username=post.author.username) }}">{{ post.author.username }}</a></p>
                <p class="post-body">
                    {% if post.body_html %}
                        {{ post.body_html | safe }}
                    {% else %}
                        {{ post.body }}
                    {% endif %}
                </p>
            </p>
        </li>
        {% endfor %}
    </ul>
    

    I have read a little bit of "Flask Web Development: Practical Web Application Development Based on Python" before. I will review it a little today. If there is anything wrong, please point it out, thank you!

    The author’s answers are all in this book. I highly recommend students who want to learn flask to read this book!

    reply
    0
  • PHP中文网

    PHP中文网2017-05-18 11:01:39

    For example, if you visit the /index page, you will definitely have a backend and a frontend
    to provide you with ideas. You can find relevant information yourself and use search engines to search for flask development

    @app.route('/index')
    def index():
        data = "从数据库读取出来的数据"
        html = []
        for item in data:
            html.append(item."列名")
        return ''.join(html)

    reply
    0
  • 为情所困

    为情所困2017-05-18 11:01:39

    You accept parameters, you can use variables in the route, or you can use the request.args.get command to get the parameters. Then execute the program to get the result. Of course, the simplest way is to splice it into a string and use return directly. Of course, the more formal way is to use render_template and cooperate with jinjia2 to render the template output.

    Let’s take a look at the quick start of flask. http://docs.jinkan.org/docs/f...

    reply
    0
  • Cancelreply