기본 콘텐츠로 건너뛰기

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

댓글

이 블로그의 인기 게시물

[GCP] Flask로 TF 2.0 MNIST 모델 서빙하기

[GCP] Flask로 TF 2.0 MNIST 모델 서빙하기 Google Cloud Platform 우선 TensorFlow 2.0을 설치하자. 머신에 직접 설치하거나 도커를 다운받아 사용, 혹은 구글 colab을 활용( https://www.tensorflow.org/install)하면 되는데, TensorFlow에서 권장하는대로 머신에 VirtualEnv를 활용해서 설치하자 ( https://www.tensorflow.org/install/pip). 설치하는 김에 Flask도 같이 설치해보자. Compute Machine 하나를 생성(크게 부담 없는 예제라 g1 instance)하고, SSH를 연결하여 실행하면 된다. $ sudo apt update $ sudo apt install python3-dev python3-pip $ sudo pip3 install -U virtualenv # 굳이 system-wide로 flask를 설치할 필요는 없지만 그렇게 했다. $ sudo pip3 install flask $ sudo pip3 install flask-restful # virtualenv 환경에서 tensorflow 2.0 설치 $ virtualenv --system-site-packages -p python3 ./venv $ source ./venv/bin/activate # sh, bash, ksh, or zsh (venv) $ pip install --upgrade pip (venv) $ pip install --upgrade tensorflow 모든 환경이 마련되었으니, 우선 MNIST 모델을 TF 2.0으로 Training하여 모델을 Save 해 두자(tf_mnist_train.py). 대략 99% 이상 정확도가 나온다! import tensorflow as tf import numpy as np # 학습 데이터 load ((train_data, train_label), (eval_data, eval_label)) = tf....

스프링 프레임워크(Spring Framework)란?

스프링 프레임워크(Spring Framework)란? "코드로 배우느 스프링 웹 프로젝트"책을 개인 공부 후 자료를 남기기 위한 목적이기에 내용 상에 오류가 있을 수 있습니다. '스프링 프레임워크'가 무엇인지 말 할 수 있고, 해당 프레임워크의 특징 및 장단점을 설명할 수 잇는 것을 목표로합니다. 1. 프레임워크란? 2. 스프링 프레임워크 "뼈대나 근간을 이루는 코드들의 묶음" Spring(Java의 웹 프레임워크), Django(Python의 웹 프레임워크), Flask(Python의 마이크로 웹 프레임워크), Ruby on rails(Ruby의 웹 프레임워크), .NET Framework, Node.js(Express.js 프레임워크) 등등. 프레임워 워크 종류 : 3. 개발 시간을 단축할 수 있다. 2. 일정한 품질이 보장된 결과물을 얻을 수 있다. 1. 실력이 부족한 개발자라 허다러도 반쯤 완성한 상태에서 필요한 부분을 조립하는 형태의 개발이 가능하다. 프레임워크를 사용하면 크게 다음 3가지의 장점 이 있습니다. 프레임워크 이용 한다는 의미 : 프로그램의 기본 흐름이나 구조를 정하고, 모든 팀원이 이 구조에 자신의 코드를 추가하는 방식으로 개발 한다. => 이러한 상황을 극복하기 위한 코드의 결과물이 '프레임워크' 입니다. 개발자는 각 개개인의 능력차이가 크고, 따라서 개발자 구성에 따라서 프로젝트의 결과 차이가 큽니다. 2. 스프링 프레임워크(Spring Framework) 자바 플랫폼을 위한 오픈 소스 애플리케이션 스프링의 다른 프레임워크와 가장 큰 차이점은 다른 프레임워크들의 포용 입니다. 이는 다시말해 기본 뼈대를 흔들지 않고, 여러 종류의 프레임워크를 혼용해서 사용할 수 있다는 점입니다. 대한민국 공공기관의 웹 서비스 개발 시 사용을 권장하고 있는 전자정부 표준프레임워크 이다. 여러 프레임워크들 중 자바(JAV...