기본 콘텐츠로 건너뛰기

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

Flask.py #1 설치해보자

Flask.py #1 설치해보자 Flask는 python의 프레임워크라고 할 수 있습니다. Flask를 설치해보자! # 리눅스 -- 접기 이러면 끝 - # pip install flask $ sudo -s 리눅스 같은 경우는 이미 파이썬이 설치가 되어 있을겁니다. # 리눅스 -- 접기 # 맥 -- 접기 이러면 끝 - $ sudo pip install flask 설치가 끝낫으면 Terminal.app 을 열어줍시다. 로 접속하여 파이썬을 설치해 줍니다. [ https://www.python.org/ ] # 맥 -- 접기 # 윈도우 -- 접기 [ https://www.python.org/ ] 로 접속하여 파이썬을 설치해 줍니다. 설치가 끝났으면 [ 고급설정 ] - [ 환경변수 ] - [ 시스템 변수 ] 에서 Path를 찾아줍니다. Path를 찾으셧다면 편집을 누르고 파이썬의 설치 경로와 파이썬 폴더 내의 Script 폴더를 입력해 줍시다. 환경변수까지 끝나셧다면 cmd 창을 키시고 pip install flask 이러면 flask 설치가 끝나게 됩니당 from http://chocoweb.tistory.com/14 by ccl(A) rewrite - 2020-03-07 13:54:54