recentpopularlog in

kme : flask   206

« earlier  
Automatic App Deployment with "git push" - Benjamin Gleitzman's Blog
When deploying pet projects on remote servers, I dislike the extra step of logging into the remote machine to execute a git pull (and perhaps a server reload) every time I push new code. Sure there’s Jenkins and all sorts of bazooka-like solutions, but this is a knife fight. Poking around an old PHP repo, I found a nifty line of code that will update your app via a URL endpoint.
<code class="language-bash"><?php `git pull`;</code>
Drop that into secret-update-url.php and now all you have to do is visit to get the latest version of your code on the site. Going a step further, you can set up a webhook to have Github hit the URL for you.
webdevel  git  php  deployment  automation  python  flask 
8 weeks ago by kme
GitHub - marshmallow-code/flask-marshmallow: Flask + marshmallow for beautiful APIs
Flask + marshmallow for beautiful APIs. Contribute to marshmallow-code/flask-marshmallow development by creating an account on GitHub.
python  flask  rest  api  framework  library 
june 2019 by kme
jinja string match - Google Groups |
In a test pillar:
<code class="language-jinja">
{% if 'node3' in grains["id"] %}
test: yayaya matches node3
{% else %}
test: nonono
{% endif %}
flask  jinja  templates  syntax  webdevel  webdesign  solution 
june 2018 by kme
python - Flask url_for generating http URL instead of https - Stack Overflow |
<code class="language-python">
viewarg1=1, ...)
flask  flask-admin  annoyance  sortof  solution 
june 2018 by kme
Fixers — Werkzeug Documentation (0.12) |
This wasn't the solution to any of the stupid mixed-content problems I ran into at work--yet.
flask  proxy  loadbalancer  maybesolution 
june 2018 by kme
python click help formatting newline - Stack Overflow |

Your newlines are not being preserved because the epilog writer does word wrapping. This can be solved with a subclass to click.Group, by creating a format_epilog() which does not do word wrapping:
<code class="language-python">class SpecialEpilog(click.Group):
def format_epilog(self, ctx, formatter):
if self.epilog:
for line in self.epilog.split('\n'):

# Tell click to use our epilog formatter,
help='wwwwwwwwww', epilog=EPILOG, invoke_without_command=True, chain=True)
python  click  flask  solution 
april 2018 by kme
Larger Applications — Flask Documentation (0.12) |
Every Python programmer hates them, and yet we just added some: circular imports (That’s when two modules depend on each other. In this case depends on Be advised that this is a bad idea in general but here it is actually fine. The reason for this is that we are not actually using the views in and just ensuring the module is imported and we are doing that at the bottom of the file.
flask  webdevel  python  circularimports  reference 
march 2018 by kme
python - catching SQLAlchemy exceptions - Stack Overflow
To catch any exception SQLAlchemy throws:
<code class="language-python">from sqlalchemy import exc
except exc.SQLAlchemyError:
pass # do something intelligent here</code>

See help(sqlalchemy.exc) and help(sqlalchemy.orm.exc) for a list of possible exceptions that sqlalchemy can raise.
python  flask  sqlalchemy  exceptionhandling  solution 
march 2018 by kme
Flask, WTForms, and duplicate IDs |
This actually works fine; I don't see what's so suboptimal about it.
Currently I do the following (I hope the code is clear enough):

<code class="language-python">
@app.route('/create', methods=('GET', 'POST'))
def create():
form = IUser()
if request.method == 'POST' and form.validate():
user = User()
except DuplicateKeyError: # I wish MySQLdb would have
# something like this
from.username.errors.append('Duplicated user name.')
flash('User "%s" created.' %['username'])
return redirect(url_for('manage.users.index'))
return render_template('users/create.html', form=form)

but it feels suboptimal. Suggestions?

See also
<code class="language-python">class Unique(object):
""" Validator that checks field uniqueness """
def __init__(self, model, field, message=None):
self.model = model
self.field = field
if not message:
message = u'This element already exists'
self.message = message

def __call__(self, form, field):
check = self.model.query.filter(self.field ==
if check:
raise ValidationError(self.message)
python  flask  wtforms  webdevel  forms  validation  solution 
march 2018 by kme
python - Flask-Admin default filters - Stack Overflow |
<code class="language-sql">from flask.ext.admin.contrib.sqla.view import ModelView, func

class PaidOrderView(ModelVew):
def get_query(self):
return self.session.query(self.model).filter(self.model.paid==True)

def get_count_query(self):
return self.session.query(func.count('*')).filter(self.model.paid==True)</code>
python  flask  flask-admin  webdevel  sqlalchemy  orm  session  query  solution 
february 2018 by kme
python - Sqlacodegen generates mixed models and tables - Stack Overflow |
It looks like what you're describing is a feature itself. sqlacodegenwill not always generate class models.

It will only form model classes for tables that have a primary key and are not association tables, as you can see in the source code:

<code class="language-python">
# Only form model classes for tables that have a primary key and are not association tables
if noclasses or not table.primary_key or in association_tables:
model = self.table_model(table)
model = self.class_model(table, links[], self.inflect_engine, not nojoined)
classes[] = model

Furthermore, in the documentation it is stated that

A table is considered an association table if it satisfies all of the following conditions:

has exactly two foreign key constraints
all its columns are involved in said constraints
python  flask-admin  flask  sqlalchemy  dba  database  model 
december 2017 by kme
python - Understanding TypeError: got multiple values for keyword argument - Stack Overflow |
What happened in my case was that I created a Click group and used the '@click.pass_context' decorator, but I forgot to accept the context (as the first argument) in the subcommands.

It actually had nothing to do with whatever's in this SO thread.
python  flask  click  errormessage  sortof  solution 
october 2017 by kme
Python jinja2 shorthand conditional - Stack Overflow |
Yes, it's possible to use inline if-expressions:

{{ 'Update' if files else 'Continue' }}
flask  jinja  templates  conditional  ternary  webdevel  solution 
september 2017 by kme
python - Flask-SQLalchemy update a row's information - Stack Overflow |
How to do a SQL "UPDATE" with Flask-SQLAlchemy:
Retrieve an object using the tutorial shown in the Flask-SQLAlchemy documentation. Once you have the entity that you want to change, change the entity itself. Then, db.session.commit().

For example:

admin = User.query.filter_by(username='admin').first() = ''

user = User.query.get(5) = 'New Name'

Flask-SQLAlchemy is based on SQLAlchemy, so be sure to check out the SQLAlchemy Docs as well.
flask  sqlalchemy  sql  dammitbrain  webdevel  solution 
september 2017 by kme
mod_wsgi (Apache) — Flask Documentation (0.12) []
Working with Virtual Environments
Virtual environments have the advantage that they never install the required dependencies system wide so you have a better control over what is used where. If you want to use a virtual environment with mod_wsgi you have to modify your .wsgi file slightly.

Add the following lines to the top of your .wsgi file:

activate_this = '/path/to/env/bin/'
execfile(activate_this, dict(__file__=activate_this))
For Python 3 add the following lines to the top of your .wsgi file:

activate_this = '/path/to/env/bin/'
with open(activate_this) as file_:
exec(, dict(__file__=activate_this))
flask  python  webdevel  webmaster  deployment  apache  mod_wsgi  config  solution 
august 2017 by kme
flask_admin.base — flask-admin 1.5.0 documentation
I think this took me like 3 months to figure out. It's not in a great spot in the docs.
flask-admin  flask  webdevel  annoyance  fuckina  solution 
august 2017 by kme
python 2.7 - Is possible to mapping view with class using mapper in SqlAlchemy? - Stack Overflow
<code class="lang-python">from sqlalchemy import orm

class ViewName(object):
def __init__(self, name): = name

orm.mapper(ViewName, v, primary_key=[])

Session = orm.sessionmaker(bind=engine)
for r in Session().query(ViewName):
print, r.number</code>
sqlalchemy  flask  dba  database  view  solution 
june 2017 by kme
Static files only work for blueprints registered with url_prefix · Issue #348 · pallets/flask · GitHub
I was able to workaround this problem by setting the app's static_folder, e.g:

from flask import Flask
from .api import blueprint as api_blueprint
from .ui import blueprint as ui_blueprint

app = Flask(__name__, static_folder = './ui/static')
app.register_blueprint(api_blueprint, url_prefix = '/api')

Basically the root app is still handling the static files, it just knows to find them in the blueprint's static folder instead of the default.
flask  bug  annoyance  workaround  webdevel 
june 2017 by kme
Flask-SQLAlchemy how to delete all rows in a single table - Stack Overflow

Try delete:


From the docs: Returns the number of rows deleted, excluding any cascades.
flask  sqlalchemy  newbie  dba  solution 
june 2017 by kme
python - Flask raises `Address already in use` running with Gunicorn - Stack Overflow
You're using Gunicorn, so you don't want to use the Flask dev server. But you're calling unconditionally. Gunicorn starts, binds the address, then imports your app, which calls and tries to start it's own server. But the address is already in use by Gunicorn.

Move into a guard block:

if __name__ == '__main__':

Or preferably remove it completely, since you should be using the flask command to run the dev server, as described in the docs.
flask  errormessage  networking  webmaster  solution 
june 2017 by kme
« earlier      
per page:    204080120160

Copy this bookmark:

to read