The Well-Grounded Python Developer How the pros use Python and Flask (Doug Farrell) (Z-Library)

Author: Doug Farrell

技术

No Description

📄 File Format: PDF
💾 File Size: 3.5 MB
35
Views
0
Downloads
0.00
Total Donations

📄 Text Preview (First 20 pages)

ℹ️

Registered users can read the full content for free

Register as a Gaohf Library member to read the complete e-book online for free and enjoy a better reading experience.

📄 Page 1
M A N N I N G Doug Farrell Foreword by Michael Kennedy How the pros use Python and Flask
📄 Page 2
2 EPILOGUE In this book, you’ll see how object-oriented programming (OOP) concepts can be used in Python code to create an application that animates a rectangle, square, and circle that inherit from the parent shape. By using inheritance, polymorphism, and composition, you’ll be able to build object hierarchies that extend and re-use common data and behavior of objects. The square, circle, and rectangle shapes drawn, and being animated, onscreen
📄 Page 3
The Well-Grounded Python Developer
📄 Page 4
(This page has no text content)
📄 Page 5
The Well-Grounded Python Developer HOW THE PROS USE PYTHON AND FLASK DOUG FARRELL Foreword by MICHAEL KENNEDY M A N N I N G SHELTER ISLAND
📄 Page 6
For online information and ordering of this and other Manning books, please visit www.manning.com. The publisher offers discounts on this book when ordered in quantity. For more information, please contact Special Sales Department Manning Publications Co. 20 Baldwin Road PO Box 761 Shelter Island, NY 11964 Email: orders@manning.com ©2023 by Manning Publications Co. All rights reserved. No part of this publication may be reproduced, stored in a retrieval system, or transmitted, in any form or by means electronic, mechanical, photocopying, or otherwise, without prior written permission of the publisher. Many of the designations used by manufacturers and sellers to distinguish their products are claimed as trademarks. Where those designations appear in the book, and Manning Publications was aware of a trademark claim, the designations have been printed in initial caps or all caps. Recognizing the importance of preserving what has been written, it is Manning’s policy to have the books we publish printed on acid-free paper, and we exert our best efforts to that end. Recognizing also our responsibility to conserve the resources of our planet, Manning books are printed on paper that is at least 15 percent recycled and processed without the use of elemental chlorine. The author and publisher have made every effort to ensure that the information in this book was correct at press time. The author and publisher do not assume and hereby disclaim any liability to any party for any loss, damage, or disruption caused by errors or omissions, whether such errors or omissions result from negligence, accident, or any other cause, or from any usage of the information herein. Manning Publications Co. Development editor: Christina Taylor 20 Baldwin Road Technical development editor: René van den Berg PO Box 761 Review editor: Aleksandar Dragosavljević Shelter Island, NY 11964 Production editor: Kathleen Rossland Copy editor: Kristen Bettcher Proofreader: Michael Beady Technical proofreader: Mathijs Affourtit Typesetter and cover designer: Marija Tudor ISBN 9781617297441 Printed in the United States of America
📄 Page 7
This book is dedicated to my partner and wife, Susan, whose encouragement, patience, and love makes all things possible.
📄 Page 8
vi brief contents 1 ■ Becoming a Pythonista 1 PART 1 GROUNDWORK .............................................................. 11 2 ■ That’s a good name 13 3 ■ The API: Let’s talk 32 4 ■ The object of conversation 48 5 ■ Exceptional events 73 PART 2 FIELDWORK ................................................................... 87 6 ■ Sharing with the internet 89 7 ■ Doing it with style 113 8 ■ Do I know you? Authentication 148 9 ■ What can you do? Authorization 172 10 ■ Persistence is good: Databases 191 11 ■ I’ve got something to say 214 12 ■ Are we there yet? 242
📄 Page 9
contents foreword xiii preface xv acknowledgments xvii about this book xix about the author xxiii about the cover illustration xxiv 1 Becoming a Pythonista 1 1.1 Commitment to learning 2 1.2 Reaching goals 3 Thinking like a developer 3 ■ Building applications 3 1.3 Using Python 4 Programming paradigms 4 ■ Creating maintainable code 5 Performance 6 ■ The language community 7 ■ Developer tooling 8 1.4 Selecting which Python version to use 9 1.5 Closing thoughts 9 PART 1 GROUNDWORK .............................................. 11 2 That’s a good name 13 2.1 Names 14 Naming things 15 ■ Naming experiment 17vii
📄 Page 10
CONTENTSviii2.2 Namespaces 20 2.3 Python namespaces 21 Built-ins level 21 ■ Module level 22 ■ Function level 25 Namespace scope 26 ■ Namespace experiment 28 3 The API: Let’s talk 32 3.1 Starting a conversation 33 A contract between pieces of code 34 ■ What’s passed as input 35 What’s expected as output 37 3.2 Function API 39 Naming 39 ■ Parameters 40 ■ Return value 42 Single responsibility 43 ■ Function length 44 Idempotence 44 ■ Side effects 44 3.3 Documentation 45 3.4 Closing thoughts 46 4 The object of conversation 48 4.1 Object-oriented programming (OOP) 49 Class definition 49 ■ Drawing with class 51 ■ Inheritance 60 Polymorphism 67 ■ Composition 68 4.2 Closing thoughts 72 5 Exceptional events 73 5.1 Exceptions 75 5.2 Handling exceptions 77 Handling an exception if the code can do something about it 77 Allowing exceptions to flow upward in your programs 78 Informing the user 78 ■ Never silence an exception 78 5.3 Raising an exception 81 5.4 Creating your own exceptions 82 5.5 Closing thoughts 84 PART 2 FIELDWORK ................................................... 87 6 Sharing with the internet 89 6.1 Sharing your work 90 Web application advantages 90 ■ Web application challenges 90
📄 Page 11
CONTENTS ix6.2 Servers 91 Request-response model 92 6.3 Web servers 93 6.4 Flask 95 Why Flask? 95 ■ Your first web server 96 ■ Serving content 98 ■ More Jinja2 features 101 6.5 Running the web server 110 Gunicorn 111 ■ Commercial hosting 111 6.6 Closing thoughts 112 7 Doing it with style 113 7.1 Application styling 114 Creating appealing styles 114 ■ Styling consistency 114 Normalizing styles 114 ■ Responsive design 115 7.2 Integrating Bootstrap 115 The previous example, now with Bootstrap 116 7.3 Helping MyBlog grow 123 The Flask app instance 123 7.4 Namespaces 127 Flask Blueprints 128 ■ Add Blueprints to MyBlog 128 Create the about page 131 ■ Refactored app instance 133 7.5 Navigation 133 Creating navigation information 133 ■ Displaying navigation information 134 ■ MyBlog’s current look 135 7.6 Application configuration 136 Configuration files 137 ■ Private information 137 7.7 Flask Debug Toolbar 137 FlaskDynaConf 138 7.8 Logging information 141 Configuration 142 7.9 Adding a favicon 144 7.10 Closing thoughts 146 8 Do I know you? Authentication 148 8.1 The HTTP protocol is stateless 149 Sessions 149
📄 Page 12
CONTENTSx8.2 Remembering someone 150 Authentication 150 ■ Logging in 158 8.3 News flash 163 Improving the login form 164 8.4 Making new friends 166 Auth Blueprint 167 ■ New user form 168 ■ Oh yeah: logging out 170 8.5 What’s next 171 9 What can you do? Authorization 172 9.1 Login/logout navigation 172 9.2 Confirming new friends 174 Sending email 174 9.3 Resetting passwords 179 9.4 User profiles 182 9.5 Security 183 Protecting routes 184 9.6 User authorization roles 184 Creating the roles 185 ■ Authorizing routes 187 9.7 Protecting forms 189 9.8 Closing thoughts 189 10 Persistence is good: Databases 191 10.1 The other half 192 Maintaining information over time 192 10.2 Accessing data 192 10.3 Database systems 198 Tables 198 ■ Relationships 199 ■ Transaction database 201 Structured query language: SQL 202 10.4 SQLite as the database 204 10.5 SQLAlchemy 205 Benefits 205 10.6 Modeling the database 206 Defining the classes 206 10.7 Creating and using the database 209
📄 Page 13
CONTENTS xiAdding data 209 ■ Using the data 211 10.8 Closing thoughts 213 11 I’ve got something to say 214 11.1 MyBlog posts 215 Modeling the database 215 11.2 Change of direction 217 11.3 Content Blueprint 218 11.4 Displaying and creating posts 218 Display handler 218 ■ Display template 219 11.5 Creating posts 220 Creation handler 220 ■ Creation form 221 ■ Creation template 221 11.6 Displaying and editing a post 222 Display handler 223 ■ Display template 223 ■ Update handler 226 ■ Update form 226 ■ Update template 227 11.7 Content to comment hierarchy 228 Modifying the post class 230 ■ Display handler 231 Display template 233 11.8 Creating comments 234 Creation template 234 ■ Creation form 236 ■ Creation handler 236 11.9 Notifying users 237 11.10 Handling site errors 238 11.11 Closing thoughts 241 12 Are we there yet? 242 12.1 Testing 243 Unit testing 243 ■ Functional testing 244 ■ End-to-end testing 244 ■ Integration testing 244 ■ Load testing 244 Performance testing 244 ■ Regression testing 244 ■ Accessibility testing 245 ■ Acceptance testing 245 12.2 Debugging 245 Reproducing bugs 245 ■ Breakpoints 246 ■ Logging 246 Bad results 246 ■ Process of elimination 247 ■ Rubber-ducking the problem 247 12.3 Tools 247
📄 Page 14
CONTENTSxiiSource control 247 ■ Optimization 248 ■ Containers 248 Databases 249 ■ Languages 249 12.4 OS environments 250 12.5 Cloud computing 250 12.6 Networking 251 12.7 Collaboration 251 12.8 Closing thoughts 251 appendix A Your development environment 253 index 263
📄 Page 15
foreword We marvel at the modern creations of very experienced software developers. Insta- gram is a polished and beautiful experience, whereas YouTube dwarfs even the largest television audiences, and it still feels like you’re the only user on the system. Both You- Tube and Instagram have Python at their core. When you first get started in programming, it’s easy to look at the challenge ahead and see a towering mountain. Fortunately, you don’t have to climb a mountain in a single bound, just as you don’t have to become a confident Python developer all at once. Software development does not require you to be a genius. You don’t need to be a mathematical wiz. Becoming a good software developer requires a strong sense of curiosity and a lot of persistence. You don’t have to take my word for it. Guido van Rossum, the inventor of Python, was interviewed for the Sing for Science podcast: Host: And you don’t have to have a mathematical inclination? Guido: That’s correct. Some sort of an inclination towards logical thinking and an attention to details is much more important than math. So if programming is not centered on math, then what do you need to be successful? You need thousands of small and understandable building blocks. Like climbing a mountain with many small steps and lots of persistence, you build YouTube by solving thousands of small and easily understandable computer problems with a few lines of understandable code. How do you discover these building blocks? You can bounce around the internet and programming tutorials, piecing them together yourself, or, like mountain climb- ing, you could hire a guide. Doug Farrell and this book of his are your guides. xiii
📄 Page 16
FOREWORDxiv Here, you will learn many building blocks. You will learn the importance of nam- ing things clearly. The function get_blog_post_by_id doesn’t need additional details to communicate its role, does it? You’ll see how to group your code into reusable blocks with functions. You will build forms to display a UI on the web with Python and Flask. You’ll use Python’s SQLAlchemy database package to read and write data from a database without the need to understand SQL (the language of relational data- bases). In the end, you’ll have a practical and real-world application built out of these many building blocks. It’ll be a fun journey, and the code will be a great resource to pull examples and ideas from as you grow in your software development career. With Doug and this book as your guides, you’ll keep climbing and, before you know it, you’ll be on the summit. Michael Kennedy is a Python enthusiast and entrepreneur. He’s the host of the Talk Python To Me and Python Bytes podcasts. Michael founded Talk Python Training and is a Python Soft- ware Foundation Fellow based in Portland, Oregon.
📄 Page 17
preface I’ve worked at many interesting and varied jobs in my life and have been fortunate enough to be a software developer for almost 40 years. In that time, I’ve learned and worked with quite a few programming languages—Pascal, Fortran, C, C++, Visual Basic, PHP, Python, and JavaScript—and applied these languages to work in quite a few industries. Using all these languages and having these experiences taught me a great deal. C taught me how to use—and certainly abuse—pointers and gave me a thirst to optimize my applications for speed. C++ taught me about object-oriented program- ming (OOP), a way of thinking in which I’m still firmly rooted. PHP was my first expo- sure to a scripting language, and it taught me that maybe it was okay not to manage everything, like memory, myself. PHP also brought with it my first dive into web devel- opment and the nascent ideas of browsers as an application platform. It’s been almost two decades since I discovered Python, and it has been my sweet spot for application development ever since. The language helped to crystalize the vague thoughts I had about development, the idea that there should be one obvious way to do things. Being able to use multiple concepts about development—like OOP, procedural, and functional programming—all in the same language is very valuable. A language can be relatively easy to learn and expressive, and yet seemingly have no ceiling on the kinds of problems it can be used to solve. Because I was excited about Python, I wanted to promote it and encourage others to jump on board. This led me to give presentations and teach classes within the orga- nizations where I worked. I also had the chance to teach Python at a STEM facility near my hometown to kids aged 8 to 16. It’s a tossup which way the lessons were actually going, as I learned a lot from the kids in the class. Each class taught me more about how to present material in a more accessible way. It was apparent when something I wasxv
📄 Page 18
PREFACExviteaching was working or not by how hard I had to work to keep the kids from switching over to Minecraft on their laptops. For the presentations and class work, I was writing my own Python material. I wanted to do more of this, which led to writing articles for RealPython.com. I wrote several well-received articles for the site, which was gratifying. Those articles were how I connected with Manning. An acquisitions editor reached out to me, and we talked about writing a Python book for them and what that would look like. The result of those conversations is this book, which will help you along your jour- ney to becoming a developer. Python is a wonderful, expressive, and enjoyable tool to bring with you. I’ve enjoyed the journey for a long time and am still doing so. That is my goal for the book, and I hope this book helps you reach your goals.
📄 Page 19
acknowledgments I’ve worked hard to make this book an informative, as well as enjoyable, read. But if it is any of these things, it’s because of the people who have contributed to its creation. Many people at Manning Publishing helped bring this book into existence. The acquisitions editor who approached me to write a book, the production people who helped shape it, the reviewers who helped refine it, and my development editors who helped me every step of the way. They helped me navigate the many facets of writing and publishing a book, and I enjoyed many conversations with them that kept me on track through the process. To all the reviewers: Alejandro Guerra Manzanares, Amanda Debler, Angelo Costa, Bernard Fuentes, Bhagvan Kommadi, Brandon Friar, Chad Miars, Christopher Kar- dell, Dan Sheikh, Danilo Abrignani, Deshuang Tang, Dhinakaran Venkat, Dirk Gomez, Eder Andres Avila Niño, Eli Mayost, Eric Chiang, Ernest Addae, Evyatar Kaf- kafi, Ezra Schroeder, Félix Moreno, Francisco Rivas, Frankie Thomas-Hockey, Ganesh Swaminathan, Garry Alan Offord, Gustavo Gomes, Hiroyuki Musha, James J. Byleckie, James Matlock, Janit Kumar Anjaria, Joaquin Beltran, John Guthrie, John Harbin, Johnny Hopkins, Jose Apablaza, Joseph Pachod, Joshua A. McAdams, Julien Pohie, Kamesh Ganesan, Katia Patkin, Keith Anthony, Kelum Prabath Senanayake, Kimberly Winston-Jackson, Koushik Vikram, Kup Sivam, Lee Harding, Leonardo Taccari, Lev Veyde, Lúcás Meier, Marc-Anthony Taylor, Marco Carnini, Marcus Geselle, Maria Ana, Michael Patin, Mike Baran, Mohana Krishna, Muhammad Sohaib Arif, NaveenKumar Namachivayam, Ninoslav Cerkez, Patrick Regan, Philip Best, Philip Patterson, Rahul Singh, Raul Murciano, Raymond Cheung, Richard Meinsen, Robert Kulagowski, Rod- ney Weis, Roman Zhuzha, Romell Ian De La Cruz, Samvid Mistry, Sandeep Dhameja, Sanjeev Kilarapu, Satej Kumar Sahu, Sergiu Raducu, Shankar Swamy, Stanley Anozie,xvii
📄 Page 20
ACKNOWLEDGMENTSxviiiStefan Turalski, Teddy Hagos, Vidhya Vinay, and Vitosh Doynov, your suggestions helped make this a better book. I also want to thank Samantha Stone, a young editor I only know virtually. Paul Chayka, the executive director of Robotics & Beyond, a local STEM education center, introduced me to her. Samantha was a high school member of R&B who volunteered to review the book while it was in progress. She proved to have outstanding editorial skills, honest and forthright feedback, and a great source of clarity for what worked and didn’t in my writing. I’d also like to thank Carmine Mauriello. He and I have been friends for decades and colleagues a few times working for the same organizations. Almost from the get- go, he told me, “You should write a book.” It’s still unclear if this was just his kind way of trying to get me to stop talking, but Carm, I appreciate the encouragement all the same. Here, at long last, is that book. I’d like to thank my mom and dad, both of whom were great writers in their own right. Mom encouraged (read that as arm-twisted) me to take a typing class in the age of the IBM Selectric Typewriter. That has proven to be one of the best skills I’ve ever learned. My dad was a great storyteller who taught me the value of writing simple declarative sentences. He was also the fastest typist I’d ever seen on an ancient Under- wood mechanical typewriter. Lastly, I would like to thank my wife, Susan, whose steady encouragement, unfail- ing patience, and most of all, love, has made all of this possible.
The above is a preview of the first 20 pages. Register to read the complete e-book.

💝 Support Author

0.00
Total Amount (¥)
0
Donation Count

Login to support the author

Login Now
Back to List