Record the pit under flask

render_template is actually very smart. It is no problem under normal circumstances, but when combined with blueprint, it brings a pit.

Let's first describe the problem. If your flask uses blueprint, then no matter what the name is set to your templates, as long as the html template file under the blueprint and the main templates

The html template file has the same name, then the program will use the template under the main program! ! !

For example, the following code will only request the main program

@app.route('/', methods=['Get'])
def index():
    return render_template('index.html')
@bp.route('/', methods=['Get'])
def index():
    return render_template('index.html')

, flask-login user management

After the Login-Manager instance is created, it is initialized in the factory function __init__.pfy file: login_manager.init__app(app).

The Login-Manager.user_loader() decorator is placed in the models.py database model, resulting in the appearance of

No user_loader has been installed for this LoginManager. Add one with the 'LoginManager.user_loader' decorator such an error, and after putting the login-manager instance and the decorator together (__init__.py), solve the problem

login_manager.init_app(app)
 
  
from app.models import User
from app.models import load_user
@login_manager.user_loader
def load_user(user_id):
return User.query.get(int(user_id))    


2. After the blueprint is created and registered in the factory function __init__.py, a 404 NOT FOUND error occurs when running the project. The reason is that the blueprint under auth is registered first, not the blueprint under main registered first, because it is related to routing
@ main.route ( '/' )
 def index () :
 return render_template( 'index.html' , title = ' Welcome ' )     
It is actually under the main blueprint, so the problem is solved after modifying the registration order:
from app.auth import auth as auth_blueprint
from app.main import main as main_blueprint
app.register_blueprint(main_blueprint)
app.register_blueprint(auth_blueprint,url_prefix='/auth')

三、创建数据库时出现“”“RuntimeError: application not registered on db instance and no applicationbound to current context”,原因是创建的app没有注册在数据库实例上,解决方法如下:http://piotr.banaszkiewicz.org/blog/2012/06/29/flask-sqlalchemy-init_app/

四、sqlite数据库创建完成后,却无法成功创建上数据表,原因是没有导入数据表模型,可在终端中如下执行
[python]  view plain  copy
  1. E:\Python代码\myproject\hometown>venv\Scripts\activate  
  2. (venv) E:\Python代码\myproject\hometown>python manage.py shell  
  3. C:\Users\Administrator\AppData\Local\Programs\Python\Python36\lib\site-packages\flask_sqlalchemy\__init__.py:839: FSADeprecationWarning: SQLALCHEMY_TRACK_MODIFICATIONS adds significant overhead and will be disabled by default in the future.  Set it to True or False to suppress this warning.  
  4.   'SQLALCHEMY_TRACK_MODIFICATIONS adds significant overhead and '  
  5. C:\Users\Administrator\AppData\Local\Programs\Python\Python36\lib\site-packages\IPython\core\interactiveshell.py:714: UserWarning: Attempting to work in a virtualenv. If you encounter problems, please install IPython inside the virtualenv.  
  6.   warn("Attempting to work in a virtualenv. If you encounter problems, please "  
  7.   
  8. In [1]: from app.model import User  
  9.   
  10. In [2]: from app import db  
  11.   
  12. In [3]: db.create_all()  
  13.   
  14. In [4]:  

五、网站中将保存在项目静态文件中的图片的url链接保存到数据库中,然后再从数据库中读取并渲染到网页中时,由于jinjia2的语法问题以及自己运用不熟练,导致网页中不能

渲染出数据库中的图片,错误代码如下:

<div class="container">
    {% for pic in pic_items %}
        <img src="{{ url_for('static',filename='{{ pic.pic_url }}') }}"/>
    {% endfor %}
</div>
所以我在view视图文件中,将所有的图片url链接先存放到列表中,再通过列表把图片url返回网页模板,最后渲染出来

@admin.route('/info_manage')
def info_manage():
    #将数据库中的图片信息按照id字段进行排序并全部查询,返回一个列表
    piclist = Pics.query.order_by(Pics.id)
    src=[]
    #将查询到的所有图片链接保存到一个列表中
    for p in piclist:
        src.append(url_for('static',filename=p.pic_url))
    # 数据分页显示
    page_index = request.args.get('page', 1, int)
    # 定义数据页,包括数据页和每一页的数据有几行
    pagination = piclist.paginate(page_index, per_page=10, error_out=False)
    pics_items = pagination.items
    return render_template('admin/info_manage.html', pics_items=pics_items, pagination=pagination,src=src)
网页模板中,这个时候的pic就是图片的真实url链接了

<div class="container">
    {% for pic in pic_items %}
        <img src="{{ pic }}" style="width: 30px; height: 30px;"/>
    {% endfor %}
</div>


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326265872&siteId=291194637