Lightweight Django Using REST, WebSockets, and Backbone (Julia Elman, Mark Lavin) (Z-Library)

Author: Julia Elman, Mark Lavin

科学

How can you take advantage of the Django framework to integrate complex client-side interactions and real-time features into your web applications? Through a series of rapid application development projects, this hands-on book shows experienced Django developers how to include REST APIs, WebSockets, and client-side MVC frameworks such as Backbone.js into new or existing projects. Learn how to make the most of Django's decoupled design by choosing the components you need to build the lightweight applications you want. Once you finish this book, you'll know how to build single-page applications that respond to interactions in real time. If you're familiar with Python and JavaScript, you're good to go.

📄 File Format: PDF
💾 File Size: 4.7 MB
12
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
Julia Elman & Mark Lavin Lightweight Django USING REST, WEBSOCKETS & BACKBONE www.it-ebooks.info
📄 Page 2
PY THON/ WEB DEVELOPMENT Lightweight Django ISBN: 978-1-491-94594-0 US $39.99 CAN $41.99 “ A great resource for going beyond traditional apps and learning how Django can power the backend of single-page web applications.” —Aymeric Augustin Django core developer, CTO, oscaro.com “ Such a good idea—I think this will lower the barrier of entry for developers even more… the more I read, the more excited I am!” —Barbara Shaurette Python Developer, Cox Media Group Twitter: @oreillymedia facebook.com/oreilly How can you take advantage of the Django framework to integrate complex client-side interactions and real-time features into your web applications? Through a series of rapid application development projects, this hands-on book shows experienced Django developers how to include REST APIs, WebSockets, and client-side MVC frameworks such as Backbone.js into new or existing projects. Learn how to make the most of Django’s decoupled design by choosing the components you need to build the lightweight applications you want. Once you finish this book, you’ll know how to build single-page applications that respond to interactions in real time. If you’re familiar with Python and JavaScript, you’re good to go. ■ Learn a lightweight approach for starting a new Django project ■ Break reusable applications into smaller services that communicate with one another ■ Create a static, rapid prototyping site as a scaffold for websites and applications ■ Build a REST API with django-rest-framework ■ Learn how to use Django with the Backbone.js MVC framework ■ Create a single-page web application on top of your REST API ■ Integrate real-time features with WebSockets and the Tornado networking library ■ Use the book’s code-driven examples in your own projects Julia Elman, a frontend developer and tech education advocate, started learning Django in 2008 while working at World Online. She is one of the co-founders for Girl Develop It RDU and PyLadies RDU, organizations that have helped over 850 women learn to program. Mark Lavin is Technical Director at Caktus Consulting Group in Durham, North Carolina. He came to Python web development after years of pricing derivatives on Wall Street. Mark maintains several open source projects related to Django development. Lightw eight D jango Elm an & Lavin Julia Elman & Mark Lavin Lightweight Django USING REST, WEBSOCKETS & BACKBONE www.it-ebooks.info
📄 Page 3
Julia Elman and Mark Lavin Lightweight Django www.it-ebooks.info
📄 Page 4
Lightweight Django by Julia Elman and Mark Lavin Copyright © 2015 Julia Elman and Mark Lavin. All rights reserved. Printed in the United States of America. Published by O’Reilly Media, Inc., 1005 Gravenstein Highway North, Sebastopol, CA 95472. O’Reilly books may be purchased for educational, business, or sales promotional use. Online editions are also available for most titles (http://safaribooksonline.com). For more information, contact our corporate/ institutional sales department: 800-998-9938 or corporate@oreilly.com. Editor: Meghan Blanchette Production Editor: Colleen Lobner Copyeditor: Rachel Monaghan Proofreader: Sonia Saruba Indexer: Wendy Catalano Cover Designer: Ellie Volckhausen Interior Designer: David Futato Illustrator: Rebecca Demarest November 2014: First Edition Revision History for the First Edition: 2014-10-24: First release See http://oreilly.com/catalog/errata.csp?isbn=9781491945940 for release details. The O’Reilly logo is a registered trademark of O’Reilly Media, Inc. Lightweight Django, the cover image, and related trade dress are trademarks of O’Reilly Media, Inc. Many of the designations used by manufacturers and sellers to distinguish their products are claimed as trademarks. Where those designations appear in this book, and O’Reilly Media, Inc. was aware of a trademark claim, the designations have been printed in caps or initial caps. While the publisher and the authors have used good faith efforts to ensure that the information and in‐ structions contained in this work are accurate, the publisher and the authors disclaim all responsibility for errors or omissions, including without limitation responsibility for damages resulting from the use of or reliance on this work. Use of the information and instructions contained in this work is at your own risk. If any code samples or other technology this work contains or describes is subject to open source licenses or the intellectual property rights of others, it is your responsibility to ensure that your use thereof complies with such licenses and/or rights. ISBN: 978-1-491-94594-0 LSI www.it-ebooks.info
📄 Page 5
Table of Contents Preface. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . vii Prerequisites. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xiii 1. The World’s Smallest Django Project. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1 Hello Django 1 Creating the View 2 The URL Patterns 2 The Settings 3 Running the Example 4 Improvements 5 WSGI Application 6 Additional Configuration 7 Reusable Template 10 2. Stateless Web Application. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13 Why Stateless? 13 Reusable Apps Versus Composable Services 14 Placeholder Image Server 14 Views 16 URL Patterns 16 Placeholder View 17 Image Manipulation 18 Adding Caching 20 Creating the Home Page View 23 Adding Static and Template Settings 23 Home Page Template and CSS 24 Completed Project 26 iii www.it-ebooks.info
📄 Page 6
3. Building a Static Site Generator. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31 Creating Static Sites with Django 31 What Is Rapid Prototyping? 32 Initial Project Layout 32 File/Folder Scaffolding 32 Basic Settings 33 Page Rendering 35 Creating Our Base Templates 35 Static Page Generator 36 Basic Styling 39 Prototype Layouts and Navigation 41 Generating Static Content 46 Settings Configuration 46 Custom Management Command 47 Building a Single Page 49 Serving and Compressing Static Files 50 Hashing Our CSS and JavaScript Files 50 Compressing Our Static Files 51 Generating Dynamic Content 54 Updating Our Templates 54 Adding Metadata 56 4. Building a REST API. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 61 Django and REST 61 Scrum Board Data Map 62 Initial Project Layout 63 Project Settings 64 No Django Admin? 66 Models 66 Designing the API 69 Sprint Endpoints 69 Task and User Endpoints 71 Connecting to the Router 74 Linking Resources 74 Testing Out the API 77 Using the Browsable API 77 Adding Filtering 81 Adding Validations 86 Using a Python Client 89 Next Steps 91 iv | Table of Contents www.it-ebooks.info
📄 Page 7
5. Client-Side Django with Backbone.js. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 93 Brief Overview of Backbone 94 Setting Up Your Project Files 95 JavaScript Dependencies 96 Organization of Your Backbone Application Files 98 Connecting Backbone to Django 100 Client-Side Backbone Routing 102 Creating a Basic Home Page View 102 Setting Up a Minimal Router 103 Using _.template from Underscore.js 104 Building User Authentication 107 Creating a Session Model 107 Creating a Login View 111 Generic Form View 117 Authenticating Routes 120 Creating a Header View 121 6. Single-Page Web Application. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 131 What Are Single-Page Web Applications? 131 Discovering the API 132 Fetching the API 132 Model Customizations 133 Collection Customizations 134 Building Our Home Page 135 Displaying the Current Sprints 135 Creating New Sprints 138 Sprint Detail Page 141 Rendering the Sprint 141 Routing the Sprint Detail 143 Using the Client State 144 Rendering the Tasks 146 AddTaskView 153 CRUD Tasks 156 Rendering Tasks Within a Sprint 156 Updating Tasks 160 Inline Edit Features 163 7. Real-Time Django. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 167 HTML5 Real-Time APIs 167 Websockets 168 Server-Sent Events 168 WebRTC 169 Table of Contents | v www.it-ebooks.info
📄 Page 8
Websockets with Tornado 169 Introduction to Tornado 170 Message Subscriptions 175 Client Communication 178 Minimal Example 179 Socket Wrapper 182 Client Connection 185 Sending Events from the Client 187 Handling Events from the Client 193 Updating Task State 195 8. Communication Between Django and Tornado. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 199 Receiving Updates in Tornado 199 Sending Updates from Django 201 Handling Updates on the Client 203 Server Improvements 204 Robust Subscriptions 204 Websocket Authentication 208 Better Updates 212 Secure Updates 214 Final Websocket Server 217 Index. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 223 vi | Table of Contents www.it-ebooks.info
📄 Page 9
Preface Since the creation of Django, a plethora of web frameworks have been created in various open source communities. Frontend-focused web frameworks such as Angular.js, Em‐ ber.js, and Backbone.js have come out of the JavaScript community and become fore‐ runners in modern web development. Where does Django fit into all of this? How can we integrate these client-side MVC frameworks into our current Django infrastructure? Lightweight Django teaches you how to take advantage of Django’s Pythonic “batteries included” philosophy. Its aim is to guide you through misconceptions that Django is too “heavy” for rapid application development. From creating the world’s smallest Django application to building a RESTful API, Lightweight Django will walk you through how to take advantage of this popular Python web framework. Why This Book? We wanted to write this book primarily because we love Django. The community is amazing, and there are so many resources to learn about Django and to develop appli‐ cations using it. However, we also felt like many of these resources, including the official Django documentation, put too much emphasis on the power of Django and not on its decoupled design. Django is a well-written framework, with numerous utilities for building web applications included. What we want this book to highlight is how you can break apart and potentially replace these components to pick and choose what best suits the application you want to build. Similarly, we wanted to break down the typical structure of Django projects and applications. Our goal is to get you to stop asking “how do I do X in Django?” and instead ask “does Django provide anything to help me do X, and if not, is something available in the community?” In addition, we wanted to answer questions about where Django fits in a Web in which more applications are built with heavy client-side interactions and real-time compo‐ nents, and paired with native mobile applications. As a framework, Django is agnostic about the client, which leaves some users feeling like Django doesn’t have an answer for vii www.it-ebooks.info
📄 Page 10
building these types of applications. We hope that this book can help shape how the community approaches these types of problems. We want to see Django and its com‐ munity continue to grow, and we want to be a part of it for many more years to come. Who Should Read This Book? If you are interested in reading this book, you are most likely an intermediate Django user. You’ve gone through the Django polls tutorial, as well as written a few basic Django web applications, and are now wondering what the next steps are. Lightweight Django serves as that next step to help outline how to utilize Django’s utilities and simplicity. Or you might be currently working on a Django project and wondering how to integrate something like Backbone.js into your project. Lightweight Django will teach you some best practices for integration and will give you a jumping-off point for building content- rich web applications. Who Should Not Read This Book? While we feel that Lightweight Django is beneficial to developers from many back‐ grounds, there might be certain people who won’t find this book interesting. For those of you who do not find writing Python and/or JavaScript pleasurable, this book is most likely not for you. All of the concepts and examples revolve around these languages, and they will be heavily used throughout each chapter. We also don’t recommend this book for those who are brand new to Django. About the Examples Each of the example projects has been carefully crafted under the theme of rapid ap‐ plication development. In each chapter, you’ll learn how to build projects that assist with project management, tools, and team collaboration. We wanted our readers to build projects that they find useful and can customize for their own use. In general, if example code is offered with this book, you may use it in your programs and documentation. You do not need to contact us for permission unless you’re reproducing a significant portion of the code. For example, writing a program that uses several chunks of code from this book does not require permission. Selling or distributing a CD-ROM of ex‐ amples from O’Reilly books does require permission. Answering a question by citing this book and quoting example code does not require permission. Incorporating a sig‐ nificant amount of example code from this book into your product’s documentation does require permission. The code samples for this title can be found here: https://github.com/lightweightdjango/ examples. viii | Preface www.it-ebooks.info
📄 Page 11
We appreciate, but do not require, attribution. An attribution usually includes the title, author, publisher, and ISBN. For example: “Lightweight Django by Julia Elman and Mark Lavin (O’Reilly). Copyright 2015 Julia Elman and Mark Lavin, 978-1-491-94594-0.” If you feel your use of code examples falls outside fair use or the permission given above, feel free to contact us at permissions@oreilly.com. Organization of This Book Chapter 1, The World’s Smallest Django Project Creating lightweight and simple web applications is the core concept in this book. In this chapter, you’ll be building a runnable, single-file “Hello World” Django application. Chapter 2, Stateless Web Application Ever wonder how placeholder image services are created? Chapter 2 walks you through how to build a stateless web application to generate placeholder image URLs. Chapter 3, Building a Static Site Generator Rapid prototyping is a useful technique for creating and scaffolding web applica‐ tions. We’ll review the purposes of this technique by creating a static site generator to help scaffold your team’s project. Chapter 4, Building a REST API REST APIs are an important part of creating web applications with rich and relevant content. This is the chapter in which we start building out a large-scale Scrum board application by using the django-rest-framework. Chapter 5, Client-Side Django with Backbone.js Chapter 5 continues with what we built in Chapter 4 by walking you through cre‐ ating a Backbone.js application that works with our newly made RESTful API. We’ll touch on each component that creates a new Backbone application and how to sync up this client-side framework with Django. Chapter 6, Single-Page Web Application Single-page web applications are a way in which we can create enriching client-side web applications. In this chapter we’ll return to our simple Backbone application and continue our progress by making it a robust single-page application. Chapter 7, Real-Time Django Creating web applications that respond to interactions in real time provides instant gratification for our users. To complete our project from the previous two chapters, we’ll add a real-time component to our Scrum board using websockets and Tornado, an asynchronous networking library written in Python. Preface | ix www.it-ebooks.info
📄 Page 12
Chapter 8, Communication Between Django and Tornado Connecting the power of Django to the robust behaviors of Tornado is an important measure in creating scalable, real-time Django applications. In this chapter, we’ll expand on our usage of the Tornado server by integrating the ability to work with Django to create a secure and interactive relationship. Conventions Used in This Book The following typographical conventions are used in this book: Italic Indicates new terms, URLs, email addresses, filenames, and file extensions. Constant width Used for program listings, as well as within paragraphs to refer to program elements such as variable or function names, databases, data types, environment variables, statements, and keywords. Constant width bold Shows commands or other text that should be typed literally by the user. Constant width italic Shows text that should be replaced with user-supplied values or by values deter‐ mined by context. Throughout the code examples, we will use an ellipsis (…) to denote that some of the previously displayed content has been skipped to shorten long code examples or to skip to the most relevant section of the code. This element signifies a tip or suggestion. This element signifies a general note. This element indicates a warning or caution. x | Preface www.it-ebooks.info
📄 Page 13
How to Contact Us Please address comments and questions concerning this book to the publisher: O’Reilly Media, Inc. 1005 Gravenstein Highway North Sebastopol, CA 95472 800-998-9938 (in the United States or Canada) 707-829-0515 (international or local) 707-829-0104 (fax) We have a web page for this book, where we list errata, examples, and any additional information. You can access this page at http://www.oreilly.com/catalog/ 0636920032502. To comment or ask technical questions about this book, send email to lightweightdjango@gmail.com. For more information about our books, courses, conferences, and news, see our website at http://www.oreilly.com. Find us on Facebook: http://facebook.com/oreilly Follow us on Twitter: http://twitter.com/oreillymedia Watch us on YouTube: http://www.youtube.com/oreillymedia Acknowledgments There are numerous people to thank and without whom this book would not be possible. We received amazing support from our editor, Meghan Blanchette. Thank you to our technical reviewers—Aymeric Augustin, Jon Banafato, Barbara Shaurette, and Marie Selvanadin— for your comments, both positive and negative, which helped to shape and focus the book. Also thank you to Heather Scherer for shep‐ herding the technical review. We are grateful to all the open source developers and contributors whose endless hours of work were needed to make these tools available for us to use and write about. Thank you to our early release readers for taking a chance on our unfinished work, dealing with typos and poor formatting, and giving feedback and correcting mistakes. Julia I would like to thank my wonderful family and close friends for their support throughout the course of writing this book. To my husband, Andrew, for believing in my abilities, Preface | xi www.it-ebooks.info
📄 Page 14
and for his constant encouragement and steadfast support during this long and bumpy journey. To my daughter, Hannah, who is my inspiration and from whom I can always grow my strength every step of the way. To my mother, Katherine, for pushing me beyond what I ever thought I was capable of doing. To my stepfather, Tom, for teaching me how to use a cordless drill, changing the oil in my car, and instilling in me the value of hard work. Thank you to my brother, Alex, and sister, Elizabeth, for always cheering me on from the sidelines. Thank you to my best friend, Jenny, for her constant love and lifelong friendship. Also, thank you to my wonderful coauthor, Mark, for his brilliance and friendship; he is one of the most talented developers I have ever collaborated with. We made it to this finish line together, and I cannot imagine going through this book writing journey with anyone else. I’d also like to thank the Python community and a few specific members who have inspired, encouraged, and/or mentored me throughout my career: James Bennett, Sean Bleier, Nathan Borror, Colin Copeland, Matt Croydon, Katie Cunningham, Selena Deckelmann, Jacob Kaplan-Moss, Jessica McKellar, Jesse Noller, Christian Metts, Lynn Root, Caleb Smith, Paul Smith, Karen Tracey, Malcolm Tredinnick, Ben Turner, and Simon Willison. Mark First and foremost, this book would not be possible without the love and support of my family. My wife, Beth, and daughter, Kennedy, put up with long hours and a grumpier and more stressed version of me than they deserve. Also thanks to my brother, Matt, for his insight and early feedback. Thank you to my parents and my brother James for their lifetime of support. Thank you to my coauthor, Julia. Our collaboration is a celebration of our friendship and mutual respect. I will forever cherish our ability to work together to create some‐ thing greater than the sum of our contributions. Finally, thank you to my coworkers at Caktus Group for your support in time, feedback, and encouragement. xii | Preface www.it-ebooks.info
📄 Page 15
Prerequisites Before we dive in, this chapter is an outline of the knowledge and software requirements you’ll need to follow the examples in this book. Python This book is aimed at developers with at least some previous Python experience, and in this book we are using Python 3. In particular, the examples have been tested to run on Python 3.3 and 3.4. Those familiar enough with Python may be able to work through this book using Python 2.7, converting the example code as needed, though it is not recommended. To read more about what is new in these versions of Python and to find installation instructions for your system, visit https://www.python.org/downloads/. We expect that you have Python installed on your local development machine, know how to edit Python files, and know how to run them. Throughout this book, when we reference Python on the command line, we will use python, though some systems or installations may require using python3 or the full version, such as python3.3 or python3.4. Similarly, when installing new packages, the examples will use pip, though some installations may require using pip3. For this book, and Python development in general, it is recommended that you create an isolated Python environment for each project using virtualenv. Without an isolated environment, installing new Python packages with pip may require root access or administrative rights on your computer. We’ll assume that if this is the case, you will prefix the pip command with sudo or any other commands you may need to gain such rights, but those prefixes will not be shown in the examples. xiii www.it-ebooks.info
📄 Page 16
Python Packages The only Python package that is required before you start this book is Django. All of the examples have been tested and written to work with Django 1.7. It is recommended that you install with pip: hostname $ pip install Django==1.7 As of August 2014, Django 1.7 was still in a release candidate phase. If the preceding installation does not work, you can install the 1.7 pre- release from the development branch with pip install https:// github.com/django/django/archive/stable/1.7.x.zip. To read more about what is new in this version of Django, visit https://docs.djangopro ject.com/en/dev/releases/1.7/. For additional installation instructions, you can also see the Django guide on installation. Additional packages will be installed throughout the chapters. Chapters 1, 2, and 3 are each independent projects and can be treated as separate virtual environments, again with Django being the only prerequisite. Chapters 4 through 8 comprise one large project, and the same virtual environment should be used for those chapters. Web Development As Django is a web framework, this book assumes you have some basic knowledge of HTML and CSS. The JavaScript examples are more in depth, and the expected level of knowledge is detailed more in the following section. A basic understanding of the HTTP protocol, in particular the usage and purpose of the various HTTP verbs (GET, POST, PUT, DELETE, etc.), is helpful. JavaScript The later chapters in this book make heavy use of JavaScript. You should also be familiar with writing JavaScript/jQuery. A developer experienced doing DOM manipulation and making AJAX calls with jQuery should be able to follow the examples using Backbone.js. If you are familiar with another client-side framework such as Angular.js, Ember.js, or Knockout.js, you will be ahead of the game. This is not meant to be a definitive guide on Backbone.js. If you are not familiar with working with JavaScript, and Backbone.js MVC architecture in particular, here are some recommended O’Reilly titles for you to read: xiv | Prerequisites www.it-ebooks.info
📄 Page 17
• JavaScript: The Definitive Guide, by David Flanagan (2011) • JavaScript: The Good Parts, by Douglas Crockford (2008) • JavaScript Patterns, by Stoyan Stefanov (2010) • Speaking JavaScript, by Axel Rauschmayer (2014) • Developing Backbone.js Applications, by Addy Osmani (2013) Browser Support The examples in this book make use of relatively new HTML5 and CSS3 APIs, and expect a modern browser. Anything below these versions has not been tested thoroughly and/or may not support the technology that we use in the examples: • IE 10+ • Firefox 28.0+ • Chrome 33.0+ You should be familiar with using the developer tools in your preferred browser to debug potential errors, see network requests, and use the JavaScript console. Additional Software Later chapters will make use of two popular databases: PostgreSQL and Redis. Brief installation instructions are noted in the chapters where needed, but you should refer to the official documentation for a more complete guide for your system. PostgreSQL is an open source relational database system that has strong support in the Django community. Any version of PostgreSQL supported by Django will work for this book. Django 1.7 supports PostgreSQL 8.4 and higher. Redis is an open source key/value cache. This book makes use of the pub/sub features of Redis and requires 2.0 and higher. Prerequisites | xv www.it-ebooks.info
📄 Page 18
www.it-ebooks.info
📄 Page 19
CHAPTER 1 The World’s Smallest Django Project How many of our journeys into using Django have begun with the official polls tutorial? For many it seems like a rite of passage, but as an introduction to Django it is a fairly daunting task. With various commands to run and files to generate, it is even harder to tell the difference between a project and an application. For new users wanting to start building applications with Django, it begins to feel far too “heavy” as an option for a web framework. What are some ways we can ease these new users’ fears to create a clean and simple start? Let’s take a moment to consider the recommended tasks for starting a Django project. The creation of a new project generally starts with the startproject command. There is no real magic to what this command does; it simply creates a few files and directories. While the startproject command is a useful tool, it is not required in order to start a Django project. You are free to lay out your project however you like based on what you want to do. For larger projects, developers benefit from the code organization provided by the startproject command. However, the convenience of this command shouldn’t stop you from understanding what it does and why it is helpful. In this chapter we’ll lay out an example of how to create a simple project using Django’s basic building blocks. This lightweight “Hello World” project will create a simple Django application using a single-file approach. Hello Django Building a “Hello World” example in a new language or framework is a common first project. We’ve seen this simple starter project example come out of the Flask community to display how lightweight it is as a microframework. In this chapter, we’ll start by using a single hello.py file. This file will contain all of the code needed to run our Django project. In order to have a full working project, we’ll 1 www.it-ebooks.info
📄 Page 20
need to create a view to serve the root URL and the necessary settings to configure the Django environment. Creating the View Django is referred to as a model-template-view (MTV) framework. The view portion typically inspects the incoming HTTP request and queries, or constructs, the necessary data to send to the presentation layer. In our example hello.py file, let’s create a simple way to execute a “Hello World” response. from django.http import HttpResponse def index(request): return HttpResponse('Hello World') In a larger project, this would typically be in a views.py file inside one of your apps. However, there is no requirement for views to live inside of apps. There is also no requirement that views live in a file called views.py. This is purely a matter of convention, but not a requirement on which to base our project’s structure. The URL Patterns In order to tie our view into the site’s structure, we’ll need to associate it with a URL pattern. For this example, the server root can serve the view on its own. Django associates views with their URL by pairing a regular expression to match the URL and any callable arguments to the view. The following is an example from hello.py of how we make this connection. from django.conf.urls import url from django.http import HttpResponse def index(request): return HttpResponse('Hello World') urlpatterns = ( url(r'^$', index), ) Now this file combines both a typical views.py file and the root urls.py file. Again, it is worth noting that there is no requirement for the URL patterns to be included in a urls.py file. They can live in any importable Python module. Let’s move on to our Django settings and the simple lines we’ll need to make our project runnable. 2 | Chapter 1: The World’s Smallest Django Project www.it-ebooks.info
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