기본 콘텐츠로 건너뛰기

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

외래어 정리

외래어 정리 [A] acacia 아카시아 academic 아카데믹 academy 아카데미 acanthus 아칸서스 accelerator 액셀러레이터 accent 악센트 acceptor 억셉터 access 액세스 accessory 액세서리 accordion 아코디언 ace 에이스 acetate 아세테이트 acetaldehyde 아세트알데히드 acetic acid 아세트(산) acetone 아세톤 acetyl 아세틸 acetylene 아세틸렌 Achilles tendon 아킬레스(건) acre 에이커 acrylic acid 아크릴(산) action 액션 active 액티브 acyl 아실 AD 에이디 adagio 아다지오 adapter 어댑터 ad + balloon 애드벌룬 address 어드레스 adenine 아데닌 adrenaline 아드레날린 advantage 어드밴티지 aerobic dance 에어로빅 댄스 aerofoil 에어로포일 aerosol 에어로졸 afghan 아프간 [편물] after + service 애프터서비스 agape 아가페 Ainu 아이누 air conditioner 에어컨(디셔너) airspray 에어스프레이 album 앨범 albumin 알부민 alcohol 알코올 aldehyde 알데히드 ALGOL 알골 algorism 알고리즘 alibi 알리바이 alkali 알칼리 alkaloid 알칼로이드 Allah 알라 allegory 알레고리 allegretto 알레그레토 allegro 알레그로 alleluia 알렐루야 Allergie 알레르기 alligator 앨리게이터 all-in-one 올인원 almond 아몬드 aloha 'oe 알로하 오에 Alpenhorn 알펜호른 alpha 알파 alphabet 알파벳 ...