Skip to content

Develop FAQ

Lawrence Liu edited this page Jan 14, 2017 · 43 revisions
  • How to join to table which has multiple foreign key to current table?
# For example if we would like to query for PurchaseOrder via EnumValue
# But there are more than one foreign key from Purchase Order to EnumValue
# Such as: status and type
# If there's only one reference, we could use .join(EnumValue)
# But if there's multiple foreign key, we need to use
# .join(PurchaseOrder.status)
status_id = Column(Integer, ForeignKey('enum_values.id'), nullable=False)
status = relationship('EnumValues', foreign_keys=[status_id])

type_id = Column(Integer, ForeignKey('enum_values.id'), nullable=False)
type = relationship('EnumValues', foreign_keys=[type_id])

@staticmethod
def status_filter(status_codes):
    from app.models.enum_values import EnumValues
    return db.session.query(PurchaseOrder) \
        .join(PurchaseOrder.status).filter(EnumValues.code.in_(status_codes))
  • How to delete a field from edit_form or create_form in flask_admin?
def create_form(self, obj=None):
    form = super(ModelView, self).create_form(obj)
    if not is_super_admin(): # Delete a field from UI.
        delattr(form, "organization") #--> Key point is delattr method invoke.
    return form

Reference: https://github.com/flask-admin/flask-admin/issues/1244

  • What's the priority of babel settings?
# Highest, per user setting can be done by this method
    @babel.localeselector
    def get_locale():
        """
        Put your logic here. Application can store locale in
        user profile, cookie, session, etc.
        This is the setting actually take effective
        """
        return 'zh_CN' if current_app.config['DEBUG'] else request.accept_languages.best_match(['zh_CN', 'en_US'])

# Default setting per initialisation of babel
def init_babel(flask_app):
    from flask_babelex import Babel
    # return Babel(default_locale='zh_Hans_CN', app=flask_app)

# Default setting per flask instance
BABEL_DEFAULT_LOCALE = 'en_US'
BABEL_DEFAULT_TIMEZONE = 'CST'
  • How to define date picker in UI with no time in flask-admin?
# Define 
    birthday = Column(Date, nullable=True)
# Rather than 
    join_date = Column(DateTime, nullable=False)
# in the SQLAlchemy model.
  • How to add values to a table and let it get correct primary key?
# Get current available minimal primary key   
res = op.get_bind().execute('SELECT max(id)+1 FROM enum_values')
results = res.fetchall()
cm = 29
for r in results:
    cm = r[0]
  • How to add a not nullable column to DB schema using alembic?
# Add the column and set nullable to True
op.alter_column('photo_collection', 'price',
                existing_type=sa.NUMERIC(precision=8, scale=2),
                nullable=True)
# Update the field to a dummy value(or something calculated by other columns)
op.execute('UPDATE "photo_collection" SET "price" = 0')
# Set the column nullable to False
op.alter_column('photo_collection', 'price', nullable=False)
  • How to call filters chain in jinja2 template?
# Just chain them by | as below
{{ m.content|substring('left',80)|safe or '' }}
  • How to get current request url in jinja2 template?
<!-- Use request.path 
E.g. if the current URL is http://www.domain.com/example/1/2
{{ request.path }} works and prints /example/1/2
Decide whether you are in a specific page
-->
{% if request.path == url_for('xxx', param1='xxx') %}
  • How to query multiple tables in SQLAlchemy ORM
# Join Order table with Request table via attribute request
# Join Order table with EnumValues table via attribute status
order_query = AppInfo.get_db().session.query(Order) \
    .outerjoin(Request, Order.request).outerjoin(EnumValues, Order.status)
  • Optional flask URL parameter By the follow definition, we can make both obj_type and status_code optional url parameter.
@app.route("/orders/")
@app.route("/orders/<obj_type>/")
@app.route("/orders/<obj_type>/<status_code>")
@login_required
def orders(obj_type="request", status_code='draft'):
  • CSS selector selecting elements NOT having a certain class?
:not(.printable) {
    /* Styles */
}
div:not(.class) {
  color: red;
}
  • How to get last day of one month in Python?
# monthrange(year, month)
# Returns weekday of first day of the month and number of days in month, 
# for the specified year and month.
# calendar.monthrange(2008,2)
# --> (4, 29)
calendar.monthrange(year, month)[1]
  • How to filter there's any record exists in the many side of one to many relation in SQLAlchemy?
# Key point is PhotoCollection.photos.any()
PhotoCollection.query.filter(PhotoCollection.photos.any()).all()
  • How to write a custom filter for jinja2 in flask?

This is a good introduction

#The actual logic
def _jinja2_filter_substring(string, direction="left", length='100'):
    if string is None:
        return ''
    if direction == "left":
        if length >= len(string):
            return string
        return string[0:length]
    elif direction == "right":
        if length >= len(string):
            return ''
        return string[length:len(string)]

# Register it to flask
app.jinja_env.filters['substring'] = _jinja2_filter_substring

<!--Use it in jinja2 template-->
{{ c.introduce|substring("left", 90) }}
{{ c.introduce|substring("right", 90) }}
  • How to keep a layer in the screen?
.class_name {
  position: fixed;
  top: 50px;
 }
  • How to set a block element xx% width and align it center?
.class_name {
  position: absolute/fixed;
  width: xx%;
  left: (100-xx)/2%;
  text-align:center
}
  • Reset POSTGRESQL in Heroku
heroku pg:reset DATABASE --app $APP_NAME
  • How to get multi select list from web page in flask?
multiselect = request.form.getlist('mymultiselect')

or if a form is defined, just use follow syntax and a list will be returned.

data = <defined_form>.mymultiselect.data
  • How to construct or filter in SQLAchemely?
or_(PhotoCollection.price >= min_price, PhotoCollection.price.is_(None))
  • How to disable access log in flask development?
import logging
# Disable werkzeug log
log = logging.getLogger('werkzeug')
log.setLevel(logging.ERROR)
  • Format decimal in javascript
parseFloat(Math.round(num * 100) / 100).toFixed(2);
  • Rename git branch locally and remotely?
git branch -m old_branch new_branch         # Rename branch locally    
git push origin :old_branch                 # Delete the old branch    
git push --set-upstream origin new_branch   # Push the new branch, set local branch to track the new remote
  • URL for PostgreSQL if there's no password?
postgres://db_username@db_host/db_name
  • How to show all PostgreSQL table column in PSQL?
select * from table_name where false;
  • How to generate unique uuid?
uuid.uuidxxx(xxx could be 1 to 5 depends on the algorithm)
  • How to define variable in jinja2 template?
{% set testing = 'it worked' %} <!-- Define variable -->
{% set another = testing %} <!-- Define variable -->
{{ another }} <!-- Output variable -->
  • How to resolve the issue all non-ascii characters being truncate by flask secure_filename method?
# Use uuid.uuidxxx to generate a unique filename first, and then,
# when save the file, pass in name 
name, ext = os.path.splitext(image_file.filename)
safe_name = str(uuid.uuid4()) + ext
filename = service.save(image_file, name=safe_name)
  • How to get one object by primary key using flask-sqlalchemy? Click here for Official document
User.query.get(1)
  • How to get count of list in jinja2 tempalte?
{% if alist |length ==0 %}  or  {% if alist |count ==0 %}
  • How to format date in jinja2 template?
# Format to string like 2014-03-14
{{ user.birthday.strftime('%Y-%m-%d')
  • How to avoid output None for None object in jinja2 template?
{{ user.mobile_phone or ''}}
  • How to switch heroku app locally? Just change the .git/config file and the follow URL parts:
[remote "heroku"]
    url = https://git.heroku.com/betterlife-flask-dev.git
    fetch = +refs/heads/*:refs/remotes/heroku/*
  • How to resolve 400 bad request error caused by request parameter not exist in post form? Use request.form.get('gender') rather than request.form['gender'] to get value of the field on server side.

  • How to test whether a variable is defined in jinja2 template?

{% if variable is defined %}
  • How to edit multiple lines in emacs?
  1. Find the content to be edit via find.
  2. Use the follow shortcut to edit multiple occurs.
C-x r t