35,99 €
Flask is a small and powerful web development framework for Python. It does not presume or force a developer to use a particular tool or library. Flask supports extensions that can add application features as if they were implemented in Flask itself. Flask’s main task is to build web applications quickly and with less code. With its lightweight and efficient web development framework, Flask combines rapid development and clean, simple design.
This book will take you through the basics of learning how to apply your knowledge of Python to the web.
Starting with the creation of a “Hello world” Flask app, you will be introduced to the most common Flask APIs and Flask’s interactive debugger. You will learn how to store and retrieve blog posts from a relational database using an ORM and also to map URLs to views. Furthermore, you will walk through template blocks, inheritance, file uploads, and static assets.
You will learn to authenticate users, build log in/log out functionality, and add an administrative dashboard for the blog. Moving on, you will discover how to make Ajax requests from the template and see how the Mock library can simplify testing complex interactions.
Finally, you will learn to deploy Flask applications securely and in an automated, repeatable manner, and explore some of the most popular Flask resources on the web.
Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:
Seitenzahl: 275
Veröffentlichungsjahr: 2015
Copyright © 2015 Packt Publishing
All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.
Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the authors, nor Packt Publishing, and its dealers and distributors will be held liable for any damages caused or alleged to be caused directly or indirectly by this book.
Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.
First published: November 2015
Production reference: 1241115
Published by Packt Publishing Ltd.
Livery Place
35 Livery Street
Birmingham B3 2PB, UK.
ISBN 978-1-78398-336-0
www.packtpub.com
Authors
Matt Copperwaite
Charles Leifer
Reviewers
Abhishek Gahlot
Burhan Khalid
Commissioning Editor
Ashwin Nair
Acquisition Editor
Subho Gupta
Content Development Editor
Mamata Walkar
Technical Editors
Siddhesh Ghadi
Siddhesh Patil
Copy Editor
Sonia Mathur
Project Coordinator
Shipra Chawhan
Proofreaders
Stephen Copestake
Safis Editing
Indexer
Mariammal Chettiyar
Production Coordinator
Conidon Miranda
Cover Work
Conidon Miranda
Matt Copperwaite graduated from the University of Plymouth in 2008 with a bachelor of science (Hons) degree in computer systems and networks. Since then, he has worked in various private and public sectors in the UK. Matt is currently working as a Python software developer and DevOps engineer for the UK Government, focusing mainly on Django. However, his first love is Flask, with which he has built several products under the General Public License (GPL).
Matt is also a trustee of South London Makerspace, a hackerspace community in South London; a cohost of The Dick Turpin Road Show, a podcast for free and open source software; and LUG Master of Greater London Linux User Group.
He has also been the technical reviewer of the Flask Framework Cookbook.
I would like to thank my new wife Marie who has been so patient throughout the production of this book.
Charles Leifer is a professional software engineer with 6 years of experience using Python. He is the author of several popular open source libraries, including Peewee ORM and Huey, a multithreaded task queue. He is also the cocreator of https://readthedocs.org, a free documentation hosting platform.
Charles developed a passion for Python while working at the Journal World. His colleagues there patiently answered his endless questions and taught him everything about the Web, Linux, open source, and how to write clean Python.
Charles maintains an active programming blog at http://charlesleifer.com.
I would like to thank my wife, Leslie, and my parents, Anne and John, for their encouragement and support.
Abhishek Gahlot is a Computer Engineer and holds a Bachelors degree in Computer Science. He loves programming in Python and Go.
He created two Web Applications Cloudtub (cloudtub.com) and Dynofy (dynofy.com). Dynofy uses the Flask framework for Web and REST API. Abhishek is very passionate about Algorithms, Artificial Intelligence and Parallel Programming.
He occasionally writes articles related to Web Engineering at blog.abhishek.it. Abhishek can be reached at <[email protected]>.
Burhan Khalid has always been tinkering with technology from his early days of XT to writing JCL on the ISPF editor, C and C++, Java, Pascal, and COBOL, to his latest favorite, Python. As a lover of technology, he is most comfortable experimenting with the next big technology stack.
By day, he works at a multinational bank in the alternative channels unit, where he gets to hack, develop, and test applications that help execute transactions across all sectors of electronic devices and channels. In addition to his work, he also contributes to open source projects. Burhan has also released a few toolkits for transaction processing.
He is an avid volunteer and has mentored Sirdab Lab (a start-up accelerator). Burhan is a frequent speaker at the local Google Developer Groups, a presenter and volunteer at StartupQ8, a start-up community. He is also actively involved with StackOverflow.
In his free time, you can find him splitting time nurturing his other passions—flight, by scheduling time in flight simulators, and photography, by uploading images to his Flickr feed.
I would like to thank my mother and father for always encouraging me; my wife for putting up with my long days at the keyboard and my ever - growing gadget collection; and my friends and colleagues for providing me with new challenges to sharpen my skills.
Special thanks to Lalith Polepeddi for contributing to the book at a stage where we needed it the most.
For support files and downloads related to your book, please visit www.PacktPub.com.
Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.PacktPub.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at <[email protected]> for more details.
At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a range of free newsletters and receive exclusive discounts and offers on Packt books and eBooks.
https://www2.packtpub.com/books/subscription/packtlib
Do you need instant solutions to your IT questions? PacktLib is Packt's online digital book library. Here, you can search, access, and read Packt's entire library of books.
If you have an account with Packt at www.PacktPub.com, you can use this to access PacktLib today and view 9 entirely free books. Simply use your login credentials for immediate access.
Welcome to Learning Flask, the book that will teach you the necessary skills to build web applications with Flask, a lightweight Python web framework. This book takes an example-driven approach that is designed to get you started quickly. The practical examples are balanced with just the right amount of background information to ensure that you understand not only the how, but also the why of Flask development.
Flask was originally released by Armin Ronacher as part of an elaborate April Fool's Day prank in 2010. The project touted itself as, "The next generation python micro web-framework," and lampooned features made popular by similar microframeworks. Although Flask was intended as a prank, the authors were caught by surprise when many people expressed serious interest in the project.
Flask is a microframework that is built on top of two excellent libraries: the Jinja2 templating engine, and the Werkzeug WSGI toolkit. Despite being a relative new-comer compared to other frameworks, such as Django, and Pylons, Flask has garnered a large and loyal following. Flask provides powerful tools for common web development tasks and encourages a bring-your-own-library approach for everything else, allowing programmers the flexibility to pick and choose the best components for their application. Every Flask app is different, and as the project's documentation states, "Flask is Fun".
The Flask microframework represents a departure in terms of design and API from most other popular Python web frameworks, which has led many developers that are new to Flask to ask, "What is the right way to build an app?" Flask does not offer any strong opinions on how we, the developers, should build our app. Instead, it provides opinions on what you need to build an app. Flask can be thought of as a collection of objects and functions to deal with common web tasks, such as routing URLs to code, processing request data, and rendering templates. While the level of flexibility that Flask provides is liberating, it can also lead to confusion and poor designs.
The purpose of this book is to help you see this flexibility as opportunity. Over the course of this book, we will be building and progressively enhancing a Flask-powered blogging site. New concepts will be introduced through the addition of new features to the site. By the end of the book, we will have created a fully-featured website, and you will have a strong working knowledge of Flask and the ecosystem of its commonly-used extensions and libraries.
Chapter 1, Creating Your First Flask Application, begins with the bold declaration, "Flask is fun", which is one of the first things that you see when you view the official Flask documentation, and in this chapter, you will get to grips with why so many Python developers agree.
Chapter 2, Relational Databases with SQLAlchemy, says that relational databases are the bedrock upon which almost all modern web applications are built. We will use SQLAlchemy, a powerful object-relational mapper that allows us to abstract away the complexities of multiple database engines. In this chapter, you will learn about how the data model that you choose early on will affect almost every facet of the code that follows.
Chapter 3, Templates and Views, covers two of the most recognizable components of the framework: the Jinja2 template language, and the URL routing framework. We will fully immerse ourselves in Flask and see our app finally start to take shape. As we progress through the chapter, our app will start looking like a proper website.
Chapter 4, Forms and Validation, shows you how to use forms to modify content on your blog directly through the site handled by the popular WTForms library. This is a fun chapter because we will add all sorts of new ways to interact with our site. We will create forms to work with our data models and learn how to receive and validate user data.
Chapter 5, Authenticating Users, explains how you can add user authentication to your site. Being able to distinguish one user from another allows us to develop an entirely new class of features. For instance, we will see how to restrict access to the create, edit, and delete views, preventing anonymous users from tampering with site content. We can also display a user's draft posts to them but hide them from everyone else.
Chapter 6, Building an Administrative Dashboard, shows you how you can build an administrative dashboard for your site, using the excellent Flask-Admin. Our admin dashboard will give certain selected users the ability to manage all the content across the entire site. In essence, the admin site will be a graphical frontend for the database, supporting operations to create, edit, and delete rows in our application's tables.
Chapter 7, AJAX and RESTful APIs, uses Flask-Restless to create a RESTful API for the blogging app. A RESTful API is a powerful way of accessing your app programmatically by providing highly-structured data to represent it. Flask-Restless works very well with our SQLAlchemy models, and it also handles complex tasks, such as serialization, and result filtering.
Chapter 8, Testing Flask Apps, covers how you can write unit tests covering all parts of the blogging app. We will utilize Flask's test client to simulate "live" requests. We will also see how the Mock library can simplify testing complex interactions, such as calling third-party services, such as databases.
Chapter 9, Excellent Extensions, teaches you how to enhance your Flask installation with popular third-party extensions. We used extensions throughout the book, but we can now explore the added extra security or functionality with very little effort and can polish off your app nicely.
Chapter 10, Deploying Your Application, teaches you how to deploy your Flask applications securely and in an automated, repeatable manner. We will look at how to configure the commonly-used WSGI capable servers, such as Apache and Nginx, as well as the Python web server Gunicorn, to give you plenty of options. Then, we will see how to secure part or the entire site using SSL before finally wrapping up our application in a configuration management tool to automate our deployment.
While Python is at home on most operating systems, and we have tried to keep an operating system-agnostic approach within the book, it is advisable to use a computer running a Linux distribution or OS X when working with this book, as Python is already installed and running. The Linux distribution can be either installed on the machine or within a virtual machine. Almost any Linux distribution will do, and any recent version of Ubuntu will be fine.
This book is for anyone who wants to develop their knowledge of Python into something that can be used on the Web. Flask follows Python design principles, and it can be easily understood by anyone who knows Python and even by those who do not.
In this book, you will find a number of text styles that distinguish between different kinds of information. Here are some examples of these styles and an explanation of their meaning.
Code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles are shown as follows: "We can include other contexts through the use of the include directive."
A block of code is set as follows:
When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold:
Any command-line input or output is written as follows:
New terms and important words are shown in bold. Words that you see on the screen, for example, in menus or dialog boxes, appear in the text like this: "You should see the message Hello, Flask displayed on a blank white page."
Warnings or important notes appear in a box like this.
Tips and tricks appear like this.
Feedback from our readers is always welcome. Let us know what you think about this book—what you liked or disliked. Reader feedback is important for us as it helps us develop titles that you will really get the most out of.
To send us general feedback, simply e-mail <[email protected]>, and mention the book's title in the subject of your message.
If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, see our author guide at www.packtpub.com/authors.
Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase.
You can download the example code files from your account at http://www.packtpub.com for all the Packt Publishing books you have purchased. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.
Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you find a mistake in one of our books—maybe a mistake in the text or the code—we would be grateful if you could report this to us. By doing so, you can save other readers from frustration and help us improve subsequent versions of this book. If you find any errata, please report them by visiting http://www.packtpub.com/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata will be uploaded to our website or added to any list of existing errata under the Errata section of that title.
To view the previously submitted errata, go to https://www.packtpub.com/books/content/support and enter the name of the book in the search field. The required information will appear under the Errata section.
Piracy of copyrighted material on the Internet is an ongoing problem across all media. At Packt, we take the protection of our copyright and licenses very seriously. If you come across any illegal copies of our works in any form on the Internet, please provide us with the location address or website name immediately so that we can pursue a remedy.
Please contact us at <[email protected]> with a link to the suspected pirated material.
We appreciate your help in protecting our authors and our ability to bring you valuable content.
If you have a problem with any aspect of this book, you can contact us at <[email protected]>, and we will do our best to address the problem.
Flask is fun. This bold declaration is one of the first things you see when you view the official Flask documentation and, over the course of this book, you will come to understand why so many Python developers agree.
In this chapter we shall:
Flask is a lightweight Web framework written in Python. Flask started out as an April fool's joke that became a highly popular underdog in the Python web framework world. It is now one of the most widely used Python web frameworks for start-ups, and is becoming commonly accepted as the perfect tool for quick and simple solutions in most businesses. At its core, it provides a set of powerful libraries for handling the most common web development tasks, such as:
This book will teach you how to use these tools through practical, real-world examples. We will also discuss commonly used third-party libraries for things that are not included in Flask, such as database access and form validation. By the end of this book you will be ready to tackle your next big project with Flask.
As the documentation states, Flask is fun, but it can also be challenging, especially when you are building a large application. Unlike other popular Python web frameworks, such as Django, Flask does not enforce ways of structuring your modules or your code. If you have experience with other web frameworks, you may be surprised how writing applications in Flask feels like writing Python as opposed to the framework boilerplate.
This book will teach you to use Flask to write clean, expressive applications. As you progress through this book, you will not only become a proficient Flask developer but you will also become a stronger Python developer.
Flask is written in Python, so before we can start writing Flask apps we must ensure that Python is installed. Most Linux distributions and recent versions of OSX come with Python pre-installed. The examples in this book will require Python 2.6 or 2.7. Instructions for installing Python can be found at http://www.python.org.
If this is your first time using Python, there are a number of excellent resources available for free on the web. I would recommend Learn Python The Hard Way, by Zed Shaw, available for free online at http://learnpythonthehardway.org. Looking for more? You can find a large list of free Python resources at http://resrc.io/list/10/list-of-free-programming-books/#python.
You can verify that Python is installed and that you have the correct version by running the Python interactive interpreter from a command prompt:
At the prompt (>>>) type exit() and hit Enter to leave the interpreter.
This book will include code that is compatible with both Python 2 and Python 3 where possible. Unfortunately, since Python 3 is still relatively new as compared to Python 2, not all third-party packages used in this book are guaranteed to work seamlessly with Python 3. There is a lot of effort being put into making popular open-source libraries compatible with both versions but, at the time of writing, some libraries have still not been ported. For best results, ensure that the version of Python that you have installed on your system is 2.6 or above.
Now that you have ensured that Python is installed correctly, we will install some popular Python packages that will be used over the course of this book.
We will be installing these packages system-wide but, once they are installed, we will be working exclusively in virtual environments.
The de-facto Python package installer is pip . We will use it throughout the book to install Flask and other third-party libraries.
If you already have setuptools installed, you can install pip by simply running the following command:
After completing the installation, verify that pip is installed correctly:
The version numbers are likely to change, so for a definitive guide please consult the official instructions, which can be found at http://www.pip-installer.org/en/latest/installing.html.
Once pip is installed, we can proceed to install the most important tool in any Python developer's toolkit: virtualenv. Virtualenv makes it easy to produce isolated Python environments, complete with their own copies of system and third-party packages.
Virtualenv solves a number of problems related to package management. Imagine you have an old application that was built using a very early version of Flask, and you would like to build a new project using the most-recent version of Flask. If Flask was installed system-wide, you was be forced to either upgrade your old project or write your new project against the old Flask. If both projects were using virtualenv, then each could run its own version of Flask, with no conflicts or issues.
Virtualenv makes it easy to control which versions of the third-party package is used by your project.
Another consideration is that installing packages system-wide generally requires elevated privileges (sudo pip install foo). By using virtualenvs, you can create Python environments and install packages as a regular user. This is especially useful if you are deploying to a shared hosting environment or are in a situation where you do not have administrator privileges.
We will use pip to install virtualenv; since it is a standard Python package, it can be installed just like any other Python package. To ensure that virtualenv is installed system-wide, run the following command (it requires elevated privileges):
The version numbers are likely to change, so for a definitive guide please consult the official instructions at http://virtualenv.org.