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 http://mysite.com/secret-update-url 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 | https://groups.google.com/
In a test pillar:
<code class="language-jinja">
{% if 'node3' in grains["id"] %}
test: yayaya matches node3
{% else %}
test: nonono
{% endif %}
</code>
flask  jinja  templates  syntax  webdevel  webdesign  solution 
june 2018 by kme
python - Flask url_for generating http URL instead of https - Stack Overflow | https://stackoverflow.com/
<code class="language-python">
url_for('secure_thingy',
_external=True,
_scheme='https',
viewarg1=1, ...)
</code>
flask  flask-admin  annoyance  sortof  solution 
june 2018 by kme
Fixers — Werkzeug Documentation (0.12) | http://werkzeug.pocoo.org/
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 | https://stackoverflow.com/

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:
formatter.write_paragraph()
for line in self.epilog.split('\n'):
formatter.write_text(line)

# Tell click to use our epilog formatter
@click.group(cls=SpecialEpilog,
help='wwwwwwwwww', epilog=EPILOG, invoke_without_command=True, chain=True)
....
</code>
python  click  flask  solution 
april 2018 by kme
Larger Applications — Flask Documentation (0.12) | http://flask.pocoo.org/
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 views.py depends on __init__.py). 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 __init__.py 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
db.add(user)
try:
db.commit()
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 | http://librelist.com/
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'))
@require('admin')
def create():
form = IUser()
if request.method == 'POST' and form.validate():
user = User()
form.update(user)
try:
user.create()
except DuplicateKeyError: # I wish MySQLdb would have
# something like this
from.username.errors.append('Duplicated user name.')
else:
flash('User "%s" created.' % form.data['username'])
return redirect(url_for('manage.users.index'))
return render_template('users/create.html', form=form)
</code>

but it feels suboptimal. Suggestions?

See also http://librelist.com/browser/flask/2011/6/17/flask-wtforms-and-duplicate-ids/#f67efd2ff1bdab437b7a06c5d621a666:
<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 == field.data).first()
if check:
raise ValidationError(self.message)
</code>
python  flask  wtforms  webdevel  forms  validation  solution 
march 2018 by kme
python - Flask-Admin default filters - Stack Overflow | https://stackoverflow.com/
<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 | https://stackoverflow.com/
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 table.name in association_tables:
model = self.table_model(table)
else:
model = self.class_model(table, links[table.name], self.inflect_engine, not nojoined)
classes[model.name] = model
</code>

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 | https://stackoverflow.com/
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 | https://stackoverflow.com/
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 | https://stackoverflow.com/
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()
admin.email = 'my_new_email@example.com'
db.session.commit()

user = User.query.get(5)
user.name = 'New Name'
db.session.commit()

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) [http://flask.pocoo.org/]
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/activate_this.py'
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/activate_this.py'
with open(activate_this) as file_:
exec(file_.read(), 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):
self.name = name

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

Session = orm.sessionmaker(bind=engine)
for r in Session().query(ViewName):
print r.id, 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(ui_blueprint)
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:

models.User.query.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 app.run unconditionally. Gunicorn starts, binds the address, then imports your app, which calls app.run and tries to start it's own server. But the address is already in use by Gunicorn.

Move app.run into a guard block:

if __name__ == '__main__':
app.run()

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