Showing posts with label Flask. Show all posts
Showing posts with label Flask. Show all posts

Friday, December 12, 2014

Project Enferno: RAD framework with Python / Flask / MongoDB / Redis

By Vasudev Ram



Just saw this via Python Weekly's email newsletter. Enferno seems to be a RAD (Rapid Application Development) framework of sorts, using Python, Flask, some Flask extensions, MongoDB AND MongoEngine, and Redis.

Enferno framework

I've worked on a project or two using Python, Flask and MongoDB (which is a NoSQL database), and found it a useful combination for developing apps relatively quickly. Enferno may be worth checking out, which I will do sometime later and may then blog about it.

Here is an article about NoSQL by Martin Fowler that may be of interest to newcomers to the field. Fowler and Pramod Sadalage have also written a book, NoSQL Distilled, which is linked to from Fowler's NoSQL article page. I've read Fowler's earlier book UML Distilled, a small and useful summary of UML, and it looks from the title that their NoSQL book may be on the same lines.

- Vasudev Ram - Dancing Bison Enterprises

Signup for email about interesting new stuff from me.

Contact Page

Other Python posts | Posts about xtopdf

Sunday, November 17, 2013

Book review: Instant Flask Web Development

By Vasudev Ram



Flask is a Python micro-framework that is fairly popular.
I had first blogged about it a couple of years ago, here:

Flask, new Python microframework

Recently, I had been working on a commercial Flask project for some time, when Packt Publishing asked me if I would review one of their books, Instant Flask Web Development. I did it. The review is below.

Review of book "Instant Flask Web Development", author Ron DuPlain, publisher Packt Publishing:

The book seems to be meant for people who already have some experience with Python.
Some parts of it that cover using Twitter Bootstrap and CSS in Flask templates, will also need knowledge of those topics.

Starts with a simple Hello World Flask app and explains some of the concepts involved.

Some of the topics covered in the book are:
- making a simple Flask app
- mapping URLs to functions (a.k.a. routing)
- HTTP request and response handling
- using databases, static file handling, and form and file uploads
- database CRUD (Create / Read / Update / Delete) operations
- sessions and authentication
- error handling
- deploying Flask apps using nginx and gunicorn

Uses Flask-Script to create command line tools to manage the Flask apps created.

Flask-Script is a Flask extension that provides support for writing external scripts in Flask.

(Flask has an facility for writing extensions that add to the functionality of the base Flask package, and there are multiple such extensions available.)

The book then starts on a scheduling application, which is used as a tutorial to illustrate various Flask features. This app allows the user to Create, Read, Update, Delete (i.e. CRUD) and List appointment records.

It shows how the use the route decorator of the Flask app object, to map various URLs that the app supports, to functions of the app that implement the actions specified by those URLs.

I noticed what seems to be an error in this section; in the middle of the code that maps the URLs to functions, there is this line:
@app.route(...) and def appointment_edit(...).
which is probably an inadvertent copy/paste from some of the text. But it would make the code fail to run, if copied as is from the ebook.

They do specify URLs (on the Packt site) from where you can download the source code for the program examples in book, though.

The use of the Flask url_for() function is described.

There appears to be an error in this section of code:
@app.route('/appointments/<int:appointment_id>/')
def appointment_detail(appointment_id):
    edit_url = url_for('appointment_edit',
    appointment_id=appointment_id)
    # Return the URL string just for demonstration.
    return edit_url
The function is called appointment_detail, but the url_for function is passed an argument 'appointment_edit'. In this case it would work, because it is just returning the URL string for display, not actually doing the appointment detail display.

Then it moves on to talk about how to handle different HTTP methods in Flask, as defined by the HTTP protocol, including GET, POST, etc.

It also mentions that instead of using the Flask route decorator, you can use a method, app.add_url_rule, as an alternative.

The section on using Jinja templates requires knowledge of CSS and JavaScript, and also Twitter Bootstrap and jQuery. The book gets a bit into Jinja features like macros.

Simple, Intermediate and Advanced sections are interspersed through the book (except for the first few sections, which are all Simple).

The book shows how to use some of Flask's error handling techniques, including how to generate a custom error page.

It ends with describing how to deploy a Flask app to production using nginx and gunicorn.

Other posts about Flask on this blog.

Other posts about Python on this blog.

- Vasudev Ram - Consulting and training on Python, Linux, open source




O'Reilly 50% Ebook Deal of the Day


Wednesday, September 18, 2013

PDF in a Flask


By Vasudev Ram





PDF in a Flask (pdf_flask.py) is a simple Flask web app that allows you to create a PDF file from text, over the web, by entering your text into a form and submitting it. It is written in Python, and uses my xtopdf toolkit for PDF creation, which in turn uses Reportlab.

PDF in a Flask is similar to my earlier post, PDF in a Bottle, but this app uses the Flask web framework instead of the Bottle web framework.

Here is the Python code for PDF in a Flask:
# PDF in a Flask.
# pdf_flask.py

# Description: Program to generate PDF from text, over the web,
# using xtopdf, ReportLab and the Flask web framework.
# It can be used to create short, simple PDF e-books.
# Author: Vasudev Ram - http://dancingbison.com
# Copyright 2013 Vasudev Ram 
# Tested with Python 2.7.

# Version: 0.1

import traceback
from textwrap import TextWrapper
from PDFWriter import PDFWriter
from flask import Flask, request

app = Flask(__name__)

@app.route("/pdf_book", methods=['GET', 'POST'])
def pdf_book():
    if request.method == 'GET':
        # Display the PDF book creation form.
        return '''
            <form action="/pdf_book" method="post">
                PDF file name: <input type="text" name="pdf_file_name" />

                Header: <input type="text" name="header" />
                Footer: <input type="text" name="footer" />

                Content:
                <textarea name="content" rows="15" cols="50"></textarea>

                <input type="submit" value="Submit" />

            </form>
            '''
    else:
        # Create the PDF book from the posted form content.
        try:
            # Get the needed fields from the form.
            pdf_file_name = request.form['pdf_file_name']
            header = request.form['header']
            footer = request.form['footer']
            content = request.form['content']

            # Create a PDFWriter instance and set some of its fields.
            pw = PDFWriter(pdf_file_name)
            pw.setFont("Courier", 12)
            pw.setHeader(header)
            pw.setFooter(footer)

            # Get the content field.
            # Split it into paragraphs delimited by newlines.
            # Convert each paragraph into a list of lines of
            # maximum width 70 characters.
            # Print each line to the PDF file.
            paragraphs = content.split('\n')
            wrapper = TextWrapper(width=70, drop_whitespace=False)
            for paragraph in paragraphs:
                lines = wrapper.wrap(paragraph)
                for line in lines:
                    pw.writeLine(line)

            pw.savePage()
            pw.close()
            return "OK. PDF book created in file " + pdf_file_name + ".\n"
        except Exception, e:
            traceback.print_stack()
            return "Error: PDF book not created.\n" + repr(e) + ".\n" 

if __name__ == "__main__":
    app.run(debug=True) 
    
# EOF

You can run the app with:

python pdf_flask.py

Then go to localhost:5000/pdf_book in your browser.

Enter some text into the big text box labeled Content. Also enter appropriate values into the other text boxes, such as PDF file name, header and footer.

When you click Submit, the PDF ebook will be created.

Here is a screenshot of the Guide to installing and using xtopdf, itself generated as a PDF book, using xtopdf and Python in a Flask web app.

- Vasudev Ram - Dancing Bison Enterprises

Contact me