기본 콘텐츠로 건너뛰기

Dummy to resolve the flask problems

Dummy to resolve the flask problems

This post is about flask problems that I struggled with. Hope you this is useful things when you taste it.

Issue : How to deploy a flask application on Apache2

Resolve : As you know, flask is a micro framework. It can be handled on Apache2 using WSGI module. See the reference.

Reference:

https://www.digitalocean.com/community/tutorials/how-to-deploy-a-flask-application-on-an-ubuntu-vps

Issue : Flask caused ERR_CONNECTION_ABORTED on POST

Resolve : There are lots issues for this problem in principle. It caused when browser keep sending some buffer but server doesn't want to receive.

My case is like this

(submit.html)

(submit.py)

@bp.route('/submit', methods=["GET", "POST"])

def submit():

return render_template("submit.html")

This kinda skel code to explain this.

In flask case, this can be caused when it runs as develop server such as run.py or manage.py. My flask runs on Apache2 and it works fine even my develop server still caused ERR_CONNECTION_ABORTED.

I resolved this problem using werkzeug.wsgi.LimitedStream. (See the reference)

(run.py) <- your develop server code

from flask import Flask

from werkzeug.wsgi import LimitedStream

class StreamConsumingMiddleware(object):

def __init__(self, app):

self.app = app

def __call__(self, environ, start_response):

stream = LimitedStream(

environ['wsgi.input'],

int(environ['CONTENT_LENGTH'] or 0)

)

environ['wsgi.input'] = stream

app_iter = self.app(environ, start_response)

try:

stream.exhaust()

for event in app_iter:

yield event

finally:

if hasattr(app_iter, 'close'):

app_iter.close()

app = Flask(__name__)

app.config.from_object(__name__)

app.wsgi_app = StreamConsumingMiddleware(app)

After applying this, uploading file on post works fine

Reference:

http://flask.pocoo.org/snippets/47/

Issue : How to add parameters for a specific function using url_for()

Resolve : Just add the parameters in url_for by separating comma(,)

url_for('.target_func_name', var1=foo1)

Reference:

http://stackoverflow.com/questions/7478366/create-dynamic-urls-in-flask-with-url-for

Issue : jinja2.exceptions.TemplateSyntaxError

TemplateSyntaxError: Encountered unknown tag 'url_for'. Jinja was looking for the following tags: 'endblock'. The innermost block that needs to be closed is 'block'.

Resolve : The exception cased by many reasons. In my case like,

It should be changed as

Issue : How to simply highlight active menu items in jinja

Resolve : As mentioned in the reference, because assignments outside of block in child templates are global and executed before the layout template is evaluated it's possible to define the active menu item in the child template.

: Child template

{% extends "layout.html" %}

{% set active_page = "index" %}

: Navigation template

{% set navigation_bar = [

('/', 'index', 'Index'),

('/downloads/', 'downloads', 'Downloads'),

('/about/', 'about', 'About')

] -%}

{% set active_page = active_page|default('index') -%}

...

{% for href, id, caption in navigation_bar %}

{{ caption|e }}

<% endfor %}

...

Reference:

http://jinja.pocoo.org/docs/dev/tricks/

Issue : How to generate the secret string for session

Resolve : gen_secret_key.py

import os, random, string

length = 32

chars = string.ascii_letters + string.digits + '!@#$%^&*()_+-=[]{},./?><'

rnd = random.SystemRandom()

print ''.join(rnd.choice(chars) for i in range(length))

Issue : Python Error (pymongo)

mongoengine.connection.ConnectionError: Cannot connect to database default :

False is not a read preference.

Resolve : This is kinda pymongo bug ? after downgrade, it works perfectly

$sudo pip install pymongo==2.8

Reference :

https://github.com/MongoEngine/mongoengine/issues/935

Issue : Python Error

NotRegistered: `BBBB` has not been registered in the document registry.

Importing the document class automatically registers it, has it

been imported?

Resolve : My case is as follow

class AAAA (db.document):

...

class BBBB (db.EmbeddedDocument)

...

Change to

class BBBB (db.EmbeddedDocument)

...

class AAAA (db.document):

...

Reference :

http://stackoverflow.com/questions/29434854/error-in-tumblelog-application-development-using-flask-and-mongoengine

from http://hackability.kr/52 by ccl(A) rewrite - 2020-03-06 07:54:19

댓글

이 블로그의 인기 게시물

Flask 13. pythonanywhere에 배포하기

Flask 13. pythonanywhere에 배포하기 Login: PythonAnywhere It's always a pleasure to hear from you! Ask us a question, or tell us what you love or hate about PythonAnywhere. We'll get back to you over email ASAP. Sorry, there was an error connecting to the server. Please try again in a few moments... www.pythonanywhere.com from http://ohdowon064.tistory.com/124 by ccl(A) rewrite - 2020-03-11 15:54:10

[ubuntu] FLASK_APP

[ubuntu] FLASK_APP Development/Debugging 🐞 FLASK_ENV=development FLASK_APP = app.py flask run zsh: command not found: FLASK_APP ✔️ FLASK_ENV=development FLASK_APP=app.py flask run 띄어쓰기를 해서 저런 오류를 출력할수도 있구나 😲 참고 : 108p에서 FLASK가 FKAS로 오타나있다. from http://hee-stories.tistory.com/18 by ccl(A) rewrite - 2020-03-24 17:20:11