티스토리 뷰

Projects/Flask

Dummy to resolve the flask problems

hackability 2015. 5. 18. 14:23

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)

<form action="{{ url_for('.submit') }}" method="post" enctype="multipart/form-data">

<input type="file" name="file"> <br />

<input type="submit" value="SUBMIT">

</form>


(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,


<a href="{% url_for('.test') %}">


It should be changed as 


<a href="{{ url_for('.test') }}">



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') -%}

...

<ul id="navigation">

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

<li {% if id == active_page %} class="active" {% endif %}><a href="{{ href|e }}">{{ caption|e }}</a></li>

<% endfor %}

</ul>

...


Reference:

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




IssueHow 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



댓글