python - 用flask+sqlalchemy查詢數(shù)據(jù)
問題描述
再我登陸計入到主頁面后,主頁面的數(shù)據(jù)是用form表單接收的嗎?查到的數(shù)據(jù)不知道怎么放到頁面上,有沒有什么資料推薦一下,或者是給點指導
問題解答
回答1:我想把從數(shù)據(jù)庫查到的數(shù)據(jù)顯示到頁面上,我想知道是不是用form提交上去的?找不到參考資料
我將根據(jù)這一句話來回答樓主的問題。
我先概括一下思路:用路由把SQLAlchemy查詢到的數(shù)據(jù)通過參數(shù)傳遞給render_template函數(shù),再在.html文件中用jinja2實現(xiàn)動態(tài)渲染網(wǎng)頁。
比如現(xiàn)在你有一個博客數(shù)據(jù)庫,你需要把博客的內(nèi)容顯示到主頁上,該如何顯示呢?
主要的方法其實是用jinja2來實現(xiàn),首先假設你有一個Post數(shù)據(jù)庫(已經(jīng)在models.py中定義好了的,別跟我說你不懂!!)
好吧你不懂,就像這樣:
from . import dbclass 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)
什么你不懂db是哪里import來的?是app包里__init__.py來的呀!這里懶得解釋了,直接帖個完整的init方法吧
from flask import Flaskfrom flask_bootstrap import Bootstrapfrom flask_mail import Mailfrom flask_moment import Momentfrom flask_sqlalchemy import SQLAlchemyfrom flask_login import LoginManagerfrom flask_pagedown import PageDownfrom config import configbootstrap = 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 SSLifysslify = 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
不過更改數(shù)據(jù)庫記得先運行python manager.py shell來遷移一下數(shù)據(jù)庫呀(具體的自己查去)扯遠了,我們來看樓主的問題。
首先來看路由(就是views.py)中的內(nèi)容:
@main.route(’/’, methods=[’GET’, ’POST’])def index(): #前面已經(jīng)假設了你有個Post數(shù)據(jù)庫 query = Post.query #這里使用了pagination,就是自動實現(xiàn)翻頁的一個擴展,可用可不用哈 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來動態(tài)渲染 return render_template(’index.html’, form=form, posts=posts, show_followed=show_followed, pagination=pagination)
現(xiàn)在讓我們到index.html中來看看jinja2該如何工作,不過為了讓index.html看上去盡量簡潔,我將打印Post的模塊單獨提了出來,叫_post.html,在index.html中使用只要{% include ’_posts.html’ %}即可:讓我們來看_post.html
<ul class='posts'> <!--處理從路由傳進來的posts,用一個for循環(huán)處理,語法酷似python--> {% for post in posts %} <li class='post'><p class='post-thumbnail'> <a href='http://m.cgvv.com.cn/wenda/{{ url_for(’.user’, username=post.author.username) }}'><img src='http://m.cgvv.com.cn/wenda/{{ post.author.gravatar(size=40) }}'> </a></p><p class='post-content'> <!--Post數(shù)據(jù)在這里顯示,你要的答案就在這了。核心思想就是用jinja2 --> <p class='post-date'>{{ moment(post.timestamp).fromNow() }}</p> <p class='post-author'><a href='http://m.cgvv.com.cn/wenda/{{ 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>
以前看過一點《Flask Web開發(fā):基于Python的Web應用開發(fā)實戰(zhàn)》,今天小小復習一下,如果有什么不對的地方,請大家指出,謝謝!
樓主要的答案這本書里都有,也強烈推薦想學flask的同學看看這本書呀!
回答2:比如你訪問的是/index頁面,你肯定會有一個后端,一個前端給你提供思路,你自己去找相關資料,搜索引擎搜索flask開發(fā)
@app.route(’/index’)def index(): data = '從數(shù)據(jù)庫讀取出來的數(shù)據(jù)' html = [] for item in data:html.append(item.'列名') return ’’.join(html)回答3:
你接受參數(shù),可以用路由里面的變量,也可以用request.args.get命令獲取參數(shù)。然后執(zhí)行程序獲得結果,當然最簡單的就是拼接成字符串直接用return,當然更正式的是用render_template ,配合jinjia2渲染模板輸出。
這個還是看下flask的快速入門吧。http://docs.jinkan.org/docs/f...
相關文章:
1. android - NavigationView 的側滑菜單中如何保存新增項(通過程序添加)2. 這段代碼既不提示錯誤也看不到結果,請老師明示錯在哪里,謝謝!3. 老師 我是一個沒有學過php語言的準畢業(yè)生 我希望您能幫我一下4. Thinkphp5.1報錯不支持Redis5. php7.3.4中怎么開啟pdo驅動6. ueditor上傳服務器提示后端配置項沒有正常加載,求助!!!!!7. 提示語法錯誤語法錯誤: unexpected ’abstract’ (T_ABSTRACT)8. 關于thinkphp 5.1中,ajax提交數(shù)據(jù)url的格式寫法,加花括號就出錯,請老師指點9. tp5 不同控制器中的變量調(diào)用問題10. http://run.php.cn/在線PHP程序運行結果不正確
