python - 用flask+sqlalchemy查詢數(shù)據(jù)
問(wèn)題描述
再我登陸計(jì)入到主頁(yè)面后,主頁(yè)面的數(shù)據(jù)是用form表單接收的嗎?查到的數(shù)據(jù)不知道怎么放到頁(yè)面上,有沒(méi)有什么資料推薦一下,或者是給點(diǎn)指導(dǎo)
問(wèn)題解答
回答1:我想把從數(shù)據(jù)庫(kù)查到的數(shù)據(jù)顯示到頁(yè)面上,我想知道是不是用form提交上去的?找不到參考資料
我將根據(jù)這一句話來(lái)回答樓主的問(wèn)題。
我先概括一下思路:用路由把SQLAlchemy查詢到的數(shù)據(jù)通過(guò)參數(shù)傳遞給render_template函數(shù),再在.html文件中用jinja2實(shí)現(xiàn)動(dòng)態(tài)渲染網(wǎng)頁(yè)。
比如現(xiàn)在你有一個(gè)博客數(shù)據(jù)庫(kù),你需要把博客的內(nèi)容顯示到主頁(yè)上,該如何顯示呢?
主要的方法其實(shí)是用jinja2來(lái)實(shí)現(xiàn),首先假設(shè)你有一個(gè)Post數(shù)據(jù)庫(kù)(已經(jīng)在models.py中定義好了的,別跟我說(shuō)你不懂!!)
好吧你不懂,就像這樣:
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來(lái)的?是app包里__init__.py來(lái)的呀!這里懶得解釋了,直接帖個(gè)完整的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
不過(guò)更改數(shù)據(jù)庫(kù)記得先運(yùn)行python manager.py shell來(lái)遷移一下數(shù)據(jù)庫(kù)呀(具體的自己查去)扯遠(yuǎn)了,我們來(lái)看樓主的問(wèn)題。
首先來(lái)看路由(就是views.py)中的內(nèi)容:
@main.route(’/’, methods=[’GET’, ’POST’])def index(): #前面已經(jīng)假設(shè)了你有個(gè)Post數(shù)據(jù)庫(kù) query = Post.query #這里使用了pagination,就是自動(dòng)實(shí)現(xiàn)翻頁(yè)的一個(gè)擴(kuò)展,可用可不用哈 pagination = query.order_by(Post.timestamp.desc()).paginate(page, per_page=current_app.config[’FLASKY_POSTS_PER_PAGE’],error_out=False) #這里才是重點(diǎn),簡(jiǎn)單來(lái)說(shuō)就是讓posts=Post.query.order_by(Post.timestamp.desc()) posts = pagination.items #然后用render_template傳給html,交給jinja2來(lái)動(dòng)態(tài)渲染 return render_template(’index.html’, form=form, posts=posts, show_followed=show_followed, pagination=pagination)
現(xiàn)在讓我們到index.html中來(lái)看看jinja2該如何工作,不過(guò)為了讓index.html看上去盡量簡(jiǎn)潔,我將打印Post的模塊單獨(dú)提了出來(lái),叫_post.html,在index.html中使用只要{% include ’_posts.html’ %}即可:讓我們來(lái)看_post.html
<ul class='posts'> <!--處理從路由傳進(jìn)來(lái)的posts,用一個(gè)for循環(huán)處理,語(yǔ)法酷似python--> {% for post in posts %} <li class='post'><p class='post-thumbnail'> <a href='http://www.aoyou183.cn/wenda/{{ url_for(’.user’, username=post.author.username) }}'><img src='http://www.aoyou183.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://www.aoyou183.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>
以前看過(guò)一點(diǎn)《Flask Web開發(fā):基于Python的Web應(yīng)用開發(fā)實(shí)戰(zhàn)》,今天小小復(fù)習(xí)一下,如果有什么不對(duì)的地方,請(qǐng)大家指出,謝謝!
樓主要的答案這本書里都有,也強(qiáng)烈推薦想學(xué)flask的同學(xué)看看這本書呀!
回答2:比如你訪問(wèn)的是/index頁(yè)面,你肯定會(huì)有一個(gè)后端,一個(gè)前端給你提供思路,你自己去找相關(guān)資料,搜索引擎搜索flask開發(fā)
@app.route(’/index’)def index(): data = '從數(shù)據(jù)庫(kù)讀取出來(lái)的數(shù)據(jù)' html = [] for item in data:html.append(item.'列名') return ’’.join(html)回答3:
你接受參數(shù),可以用路由里面的變量,也可以用request.args.get命令獲取參數(shù)。然后執(zhí)行程序獲得結(jié)果,當(dāng)然最簡(jiǎn)單的就是拼接成字符串直接用return,當(dāng)然更正式的是用render_template ,配合jinjia2渲染模板輸出。
這個(gè)還是看下flask的快速入門吧。http://docs.jinkan.org/docs/f...
相關(guān)文章:
1. php - 微信開發(fā)驗(yàn)證服務(wù)器有效性2. php如何獲取訪問(wèn)者路由器的mac地址3. 小程序怎么加外鏈,語(yǔ)句怎么寫!求救新手,開文檔沒(méi)發(fā)現(xiàn)4. javascript - 在 vue里面用import引入js文件,結(jié)果為undefined5. javascript - 我的站點(diǎn)貌似被別人克隆了, google 搜索特定文章,除了域名不一樣,其他的都一樣,如何解決?6. php - mysql 模糊搜索問(wèn)題7. python沒(méi)入門,請(qǐng)教一個(gè)問(wèn)題8. 求救一下,用新版的phpstudy,數(shù)據(jù)庫(kù)過(guò)段時(shí)間會(huì)消失是什么情況?9. html - 爬蟲時(shí)出現(xiàn)“DNS lookup failed”,打開網(wǎng)頁(yè)卻沒(méi)問(wèn)題,這是什么情況?10. javascript - js setTimeout在雙重for循環(huán)中如何使用?
