32,39 €
Design, build and test RESTful web services with the Django framework and Python
Django is a Python web framework that makes the web development process very easy. It reduces the amount of trivial code, which simplifies the creation of web applications and results in faster development. It is very powerful and a great choice for creating RESTful web services.
If you are a Python developer and want to efficiently create RESTful web services with Django for your apps, then this is the right book for you.
The book starts off by showing you how to install and configure the environment, required software, and tools to create RESTful web services with Django and the Django REST framework. We then move on to working with advanced serialization and migrations to interact with SQLite and non-SQL data sources. We will use the features included in the Django REST framework to improve our simple web service.
Further, we will create API views to process diverse HTTP requests on objects, go through relationships and hyperlinked API management, and then discover the necessary steps to include security and permissions related to data models and APIs. We will also apply throttling rules and run tests to check that versioning works as expected. Next we will run automated tests to improve code coverage.
By the end of the book, you will be able to build RESTful web services with Django.
This book is for Python developers who want to create RESTful web services with Django; you need to have a basic working knowledge of Django but no previous experience with RESTful web services is required.
Gaston C. Hillar is Italian and has been working with computers since he was 8 years old. Gaston has a bachelor's degree in computer science (graduated with honors) and an MBA. He is an independent consultant, a freelance author, and a speaker. He has been a senior contributing editor at Dr. Dobb's and has written more than a hundred articles on software development topics. He has received the prestigious Intel® Black Belt Software Developer award eight times. He lives with his wife, Vanesa, and his two sons, Kevin and Brandon.Sie lesen das E-Book in den Legimi-Apps auf:
Seitenzahl: 354
Veröffentlichungsjahr: 2018
Copyright © 2018 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 author, nor Packt Publishing or its dealers and distributors, will be held liable for any damages caused or alleged to have been 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.
Commissioning Editor: Amarabha BanerjeeAcquisition Editor: Reshma RamanContent Development Editor: Aditi GourTechnical Editor: Sushmeeta JenaCopy Editor:Safis EditingProject Coordinator: Hardik BhindeProofreader: Safis EditingIndexer: Aishwarya GangawaneGraphics: Jason MonteiroProduction Coordinator: Shraddha Falebhai
First published: January 2018
Production reference: 1220117
Published by Packt Publishing Ltd. Livery Place 35 Livery Street Birmingham B3 2PB, UK.
ISBN 978-1-78883-392-9
www.packtpub.com
Mapt is an online digital library that gives you full access to over 5,000 books and videos, as well as industry leading tools to help you plan your personal development and advance your career. For more information, please visit our website.
Spend less time learning and more time coding with practical eBooks and Videos from over 4,000 industry professionals
Improve your learning with Skill Plans built especially for you
Get a free eBook or video every month
Mapt is fully searchable
Copy and paste, print, and bookmark content
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.
Gaston C. Hillar is Italian and has been working with computers since he was 8 years old. Gaston has a bachelor's degree in computer science (graduated with honors) and an MBA. He is an independent consultant, a freelance author, and a speaker.
He has been a senior contributing editor at Dr. Dobb's and has written more than a hundred articles on software development topics. He has received the prestigious Intel® Black Belt Software Developer award eight times.
He lives with his wife, Vanesa, and his two sons, Kevin and Brandon.
Acknowledgements:
Norbert Mate is a web developer who started his career back in 2008. His first programming language as a professional web development was PHP, and then he moved on to JavaScript/node.js and Python/Django/Django REST framework. He is passionate about software architecture, design patterns, and clean code.
If you're interested in becoming an author for Packt, please visit authors.packtpub.com and apply today. We have worked with thousands of developers and tech professionals, just like you, to help them share their insight with the global tech community. You can make a general application, apply for a specific hot topic that we are recruiting an author for, or submit your own idea.
Preface
Who this book is for
What this book covers
To get the most out of this book
Download the example code files
Download the color images
Conventions used
Get in touch
Reviews
Installing the Required Software and Tools
Creating a virtual environment with Python 3.x and PEP 405
Understanding the directory structure for a virtual environment
Activating the virtual environment
Deactivating the virtual environment
Installing Django and Django REST frameworks in an isolated environment
Creating an app with Django
Understanding Django folders, files, and configurations
Installing tools
Installing Curl
Installing HTTPie
Installing the Postman REST client
Installing Stoplight
Installing iCurlHTTP
Test your knowledge
Summary
Working with Models, Migrations, Serialization, and Deserialization
Defining the requirements for our first RESTful Web Service
Creating our first model
Running our initial migration
Understanding migrations
Analyzing the database
Understanding the table generated by Django
Controlling, serialization, and deserialization
Working with the Django shell and diving deeply into serialization and deserialization
Test your knowledge
Summary
Creating API Views
Creating Django views combined with serializer classes
Understanding CRUD operations with Django views and the request methods
Routing URLs to Django views and functions
Launching Django's development server
Making HTTP GET requests that target a collection of instances
Making HTTP GET requests that target a single instance
Making HTTP POST requests
Making HTTP PUT requests
Making HTTP DELETE requests
Making HTTP GET requests with Postman
Making HTTP POST requests with Postman
Test your knowledge
Summary
Using Generalized Behavior from the APIView Class
Taking advantage of model serializers
Understanding accepted and returned content types
Making unsupported HTTP OPTIONS requests with command-line tools
Understanding decorators that work as wrappers
Using decorators to enable different parsers and renderers
Taking advantage of content negotiation classes
Making supported HTTP OPTIONS requests with command-line tools
Working with different content types
Sending HTTP requests with unsupported HTTP verbs
Test your knowledge
Summary
Understanding and Customizing the Browsable API Feature
Understanding the possibility of rendering text/HTML content
Using a web browser to work with our web service
Making HTTP GET requests with the browsable API
Making HTTP POST requests with the browsable API
Making HTTP PUT requests with the browsable API
Making HTTP OPTIONS requests with the browsable API
Making HTTP DELETE requests with the browsable API
Test your knowledge
Summary
Working with Advanced Relationships and Serialization
Defining the requirements for a complex RESTful Web Service
Creating a new app with Django
Configuring a new web service
Defining many-to-one relationships with models.ForeignKey
Installing PostgreSQL
Running migrations that generate relationships
Analyzing the database
Configuring serialization and deserialization with relationships
Defining hyperlinks with serializers.HyperlinkedModelSerializer
Working with class-based views
Taking advantage of generic classes and viewsets
Generalizing and mixing behavior
Working with routing and endpoints
Making requests that interact with resources that have relationships
Test your knowledge
Summary
Using Constraints, Filtering, Searching, Ordering, and Pagination
Browsing the API with resources and relationships
Defining unique constraints
Working with unique constraints
Understanding pagination
Configuring pagination classes
Making requests that paginate results
Working with customized pagination classes
Making requests that use customized paginated results
Configuring filter backend classes
Adding filtering, searching, and ordering
Working with different types of Django filters
Making requests that filter results
Composing requests that filter and order results
Making requests that perform starts with searches
Using the browsable API to test pagination, filtering, searching, and ordering
Test your knowledge
Summary
Securing the API with Authentication and Permissions
Understanding authentication and permissions in Django, the Django REST framework, and RESTful Web Services
Learning about the authentication classes
Including security and permissions-related data to models
Working with object-level permissions via customized permission classes
Saving information about users that make requests
Setting permission policies
Creating the superuser for Django
Creating a user for Django
Making authenticated requests
Making authenticated HTTP PATCH requests with Postman
Browsing the secured API with the required authentication
Working with token-based authentication
Generating and using tokens
Test your knowledge
Summary
Applying Throttling Rules and Versioning Management
Understanding the importance of throttling rules
Learning the purpose of the different throttling classes in the Django REST framework
Configuring throttling policies in the Django REST framework
Running tests to check that throttling policies work as expected
Understanding versioning classes
Configuring a versioning scheme
Running tests to check that versioning works as expected
Test your knowledge
Summary
Automating Tests
Getting ready for unit testing with pytest
Writing unit tests for a RESTful Web Service
Discovering and running unit tests with pytest
Writing new unit tests to improve the tests' code coverage
Running unit tests again with pytest
Test your knowledge
Summary
Solutions
Chapter 1: Installing the Required Software and Tools
Chapter 2: Working with Models, Migrations, Serialization, and Deserialization
Chapter 3: Creating API Views
Chapter 4: Using Generalized Behavior from the APIView Class
Chapter 5: Understanding and Customizing the Browsable API Feature
Chapter 6: Working with Advanced Relationships and Serialization
Chapter 7: Using Constraints, Filtering, Searching, Ordering, and Pagination
Chapter 8: Securing the API with Authentication and Permissions
Chapter 9: Applying Throttling Rules and Versioning Management
Chapter 10: Automating Tests
Other Books You May Enjoy
Leave a review - let other readers know what you think
Python is definitely one of the most popular programming languages. It is open source, multiplatform, and you can use it to develop any kind of application, from websites and web services to artificial intelligence and machine learning applications. You will always find a framework or a set of packages in Python to make things easier for you in any domain. It is extremely easy to work with Python and its most popular web framework, Django, in the most important and popular cloud computing providers. Hence, Python is an excellent choice for developing modern and scalable RESTful Web Services that will run on the cloud.
REST (short for Representational State Transfer) is the architectural style that has been driving modern and scalable web development recently. If you want to be part of the world that builds complex web applications and mobile apps, you will need to develop and interact with RESTful Web Services. In many situations, you will have to design and develop a RESTful Web Service from scratch and maintain the API over time. A deep knowledge of RESTful Web Services is an essential skill for any software development job.
This book covers everything you need to know to develop and test a RESTful Web Service from scratch with the latest version of Django, Django REST framework, and Python. You will work with real-life examples in combination with Python packages that will allow you to simplify tasks.
You will learn to use a huge set of tools to test and develop a uniform, high-quality, and scalable RESTful Web Services. You will use object-oriented programming and modern Python 3.6 code to favor code reuse and simplify future maintenance. You will take advantage of automated testing to ensure that the coded RESTful Web Services run as expected.
This book will allow you to create your own RESTful Web Services for any domain with Django and Django REST framework in Python 3.6 or greater. You will learn the process for the most popular Python platforms: Linux, Windows, and macOS.
This book is for Python developers who want to develop RESTful Web Services, also known as RESTful web APIs, with Python 3.6 or greater, and want to learn how to do it with the most popular Python web framework—Django.
Chapter 1, Installing the Required Software and Tools, shows how to get started in our journey toward creating RESTful Web Services with Python and its most popular web framework—Django. We will install and configure the environments, the software, and the tools required to create RESTful Web Services with Django and Django REST framework. We will learn the necessary steps in Linux, macOS, and Windows. We will create our first app with Django, we will take a first look at the Django folders, files, and configurations, and we will make the necessary changes to activate Django REST framework. In addition, we will introduce and install command-line and GUI tools that we will use to interact with the RESTful Web Services that we will design, code, and test in the forthcoming chapters.
Chapter 2, Working with Models, Migrations, Serialization, and Deserialization, describes how to design a RESTful Web Service to interact with a simple SQLite database and perform CRUD operations with toys. We will define the requirements for our web service, and we will understand the tasks performed by each HTTP method and the different scopes. We will create a model to represent and persist toys and execute migrations in Django to create the required tables in the database. We will analyze the tables and learn how to manage the serialization of toy instances into JSON representations with Django REST framework and the reverse process.
Chapter 3, Creating API Views, is about executing the first version of a simple Django RESTful Web Service that interacts with a SQLite database. We will write API views to process diverse HTTP requests on a collection of toys and on a specific toy. We will work with the following HTTP verbs: GET, POST, and PUT. We will configure the URL patterns list to route URLs to views. We will start the Django development server and use command-line tools (curl and HTTPie) to compose and send diverse HTTP requests to our RESTful Web Service. We will learn how HTTP requests are processed in Django and our code. In addition, we will work with Postman, a GUI tool, to compose and send other HTTP requests to our RESTful Web Service.
Chapter 4, Using Generalized Behavior from the APIView Class, presents different ways to improve our simple Django RESTful Web Service. We will take advantage of many features included in the Django REST framework to remove duplicate code and add many features for the web service. We will use model serializers, understand the different accepted and returned content types, and the importance of providing accurate responses to the HTTP OPTIONS requests. We will make the necessary changes to the existing code to enable diverse parsers and renderers. We will learn how things work under the hoods in Django REST framework. We will work with different content types and note how the RESTful Web Service improves compared to its previous versions.
Chapter 5, Understanding and Customizing the Browsable API Feature, explains how to use one of the additional features that Django REST framework adds to our RESTful Web Service—the browsable API. We will use a web browser to work with our first web service built with Django. We will learn to make HTTP GET, POST, PUT, OPTIONS, and DELETE requests with the browsable API. We will be able to easily test CRUD operations with a web browser. The browsable API will allow us to easily interact with our RESTful Web Service.
Chapter 6, Working with Advanced Relationships and Serialization, shows how to define the requirements for a complex RESTful Web Service in which we needed to work with drone categories, drones, pilots, and competitions. We will create a new app with Django and configure the new web service. We will define many-to-one relationships between the models, and we will configure Django to work with a PostgreSQL database. We will execute migrations to generate tables with relationships between them. We will also analyze the generated database and configure serialization and deserialization for the models. We will define hyperlinks and work with class-based views. Then, we will take advantage of generic classes and generic views that generalize and mix predefined behaviors. We will use routings and endpoints and prepare our RESTful Web Service to work with the browsable API. We will make many different HTTP requests to create and retrieve resources that have relationships between them.
Chapter 7, Using Constraints, Filtering, Searching, Ordering, and Pagination, describes the usage of the browsable API feature to navigate through the API with resources and relationships. We will add unique constraints to improve the consistency of the models in our RESTful Web Service. We will understand the importance of paginating results and configure and test a global limit/offset pagination scheme with Django REST framework. Then, we will create our own customized pagination class to ensure that requests won't be able to require a huge number of elements on a single page. We will configure filter backend classes and incorporate code into the models to add filtering, searching, and ordering capabilities to the class-based views. We will create a customized filter and make requests to filter, search, and order results. Finally, we will use the browsable API to test pagination, filtering, and ordering.
Chapter 8, Securing the API with Authentication and Permissions, presents the differences between authentication and permissions in Django, Django REST framework, and RESTful Web Services. We will analyze the authentication classes included in Django REST framework out of the box. We will follow the steps needed to provide security- and permissions-related data to models.
We will work with object-level permissions via customized permission classes and save information about users who make requests. We will configure permission policies and compose and send authenticated requests to understand how the permission policies work. We will use command-line tools and GUI tools to compose and send authenticated requests. We will browse the secure RESTful Web Service with the browsable API feature and work with a simple token-based authentication provided by Django REST framework to understand another way of authenticating requests.
Chapter 9, Applying Throttling Rules and Versioning Management, focuses on the importance of throttling rules and how we can combine them with authentication and permissions in Django, Django REST framework, and RESTful Web Services. We will analyze the throttling classes included in Django REST framework out of the box. We will follow the necessary steps to configure many throttling policies in Django REST framework. We will work with global and scope-related settings. Then, we will use command-line tools to compose and send many requests to test how the throttling rules work. We will understand versioning classes and we will configure a URL path versioning scheme to allow us to work with two versions of our RESTful Web Service. We will use command-line tools and the Browsable API to understand the differences between the two versions.
Chapter 10, Automating Tests, shows how to automate tests for our RESTful Web Services developed with Django and Django REST framework. We will use different packages, tools, and configurations to perform tests. We will write the first round of unit tests for our RESTful Web Service, run them, and measure tests code coverage. Then, we will analyze tests code coverage reports and write new unit tests to improve the test code coverage. We will understand the new tests code coverage reports and learn the benefits of a good test code coverage.
Appendix, Solutions, the right answers for the Test Your Knowledge sections of each chapter are included in the appendix.
Any computer or device capable of running Python 3.6.3 or greater in Linux, macOS, or Windows.
Any computer or device capable of running a modern web browser compatible with HTML 5 and CSS 3 to work with the Browsable API feature included in Django REST framework.
You can download the example code files for this book from your account at www.packtpub.com. If you purchased this book elsewhere, you can visit www.packtpub.com/support and register to have the files emailed directly to you.
You can download the code files by following these steps:
Log in or register at
www.packtpub.com
.
Select the
SUPPORT
tab.
Click on
Code Downloads & Errata
.
Enter the name of the book in the
Search
box and follow the onscreen instructions.
Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of:
WinRAR/7-Zip for Windows
Zipeg/iZip/UnRarX for Mac
7-Zip/PeaZip for Linux
The code bundle for the book is also hosted on GitHub at https://github.com/PacktPublishing/Django-RESTful-Web-Services. We also have other code bundles from our rich catalog of books and videos available athttps://github.com/PacktPublishing/. Check them out!
We also provide a PDF file that has color images of the screenshots/diagrams used in this book. You can download it here: http://www.packtpub.com/sites/default/files/downloads/DjangoRESTfulWebServices_ColorImages.pdf.
Feedback from our readers is always welcome.
General feedback: Email [email protected] and mention the book title in the subject of your message. If you have questions about any aspect of this book, please email us at [email protected].
Errata: Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you have found a mistake in this book, we would be grateful if you would report this to us. Please visit www.packtpub.com/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details.
Piracy: If you come across any illegal copies of our works in any form on the Internet, we would be grateful if you would provide us with the location address or website name. Please contact us at [email protected] with a link to the material.
If you are interested in becoming an author: If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, please visit authors.packtpub.com.
Please leave a review. Once you have read and used this book, why not leave a review on the site that you purchased it from? Potential readers can then see and use your unbiased opinion to make purchase decisions, we at Packt can understand what you think about our products, and our authors can see your feedback on their book. Thank you!
For more information about Packt, please visit : packtpub.com.
In this chapter, we will start our journey towards creating RESTful Web Services with Python and its most popular web framework: Django. Python is one of the most popular and versatile programming languages. There are thousands of Python packages, which allow you to extend Python capabilities to any kind of domain you can imagine. You can work with Django and packages to easily build simple and complex RESTful Web Services with Python that can run on your favorite platform.
We will leverage your existing knowledge of Python and all of its packages to code the different pieces of your RESTful Web Services and their ecosystem. We will use object-oriented features to create code that is easier to maintain, understand, and reuse. We don't need to learn another programming language, we can use the one we already know and love: Python.
In this chapter, we will install and configure the environments and the required software and tools to create RESTful Web Services with Django and Django REST framework. We will learn the necessary steps in Linux, macOS, and Windows. We will gain an understanding of the following:
Creating a virtual environment with Python 3.x and PEP 405
Understanding the directory structure for a virtual environment
Activating the virtual environment
Deactivating the virtual environment
Installing Django and Django REST framework in an isolated environment
Creating an app with Django
Understanding Django folders, files, and configurations
Installing Curl
Installing HTTPie
Installing the Postman REST client
Installing Stoplight
Installing iCurlHTTP
Throughout this book, we will be working with different packages and libraries to create RESTful Web Services, and therefore it is convenient to work with Python virtual environments. Python 3.3 introduced lightweight virtual environments and they were improved in Python 3.4. We will work with these virtual environments, and therefore you will need Python 3.4 or greater. You can read more information about PEP 405 Python Virtual Environment, that introduced the venv module, here: https://www.python.org/dev/peps/pep-0405. All the examples in this book were tested on Python 3.6.2 on Linux, macOS, and Windows.
Each virtual environment we create with venv is an isolated environment and it will have its own independent set of installed Python packages in its site directories (folders). When we create a virtual environment with venv in Python 3.4 and greater, pip is included in the new virtual environment. In Python 3.3, it was necessary to manually install pip after creating the virtual environment. Note that the instructions provided are compatible with Python 3.4 or greater, including Python 3.6.2.
In order to create a lightweight virtual environment, the first step is to select the target folder or directory for it. The following is the path we will use in the example for Linux and macOS.
The target folder for the virtual environment will be the HillarDjangoREST/01 folder within our home directory. For example, if our home directory in macOS or Linux is /Users/gaston, the virtual environment will be created within /Users/gaston/HillarDjangoREST/01. You can replace the specified path with your desired path in each command:
~/HillarDjangoREST/01
The following is the path we will use in the example for Windows. The target folder for the virtual environment will be the HillarDjangoREST\01 folder within our user profile folder. For example, if our user profile folder is C:\Users\gaston, the virtual environment will be created within C:\Users\gaston\HillarDjangoREST\01. You can replace the specified path with your desired path in each command:
%USERPROFILE%\HillarDjangoREST\01
In Windows PowerShell, the previous path would be as follows:
$env:userprofile\HillarDjangoREST\01
Now, we will create a new virtual environment with venv. In order to do so, we have to use the -m option followed by the venv module name and the desired path to make Python run this module as a script and create a virtual environment in the specified path. The instructions are different depending on the platform in which we are creating the virtual environment.
Open Terminal in Linux or macOS and execute the following command to create a virtual environment:
python3 -m venv ~/HillarDjangoREST/01
In Windows, in Command Prompt, execute the following command to create a virtual environment:
python -m venv %USERPROFILE%\HillarDjangoREST\01
If you want to work with Windows PowerShell, execute the following command to create a virtual environment:
python -m venv $env:userprofile\HillarDjangoREST\01
None of the previous commands produce any output. The script created the specified target folder and installed pip by invoking ensurepip because we didn't specify the --without-pip option.
The specified target folder has a new directory tree that contains Python executable files and other files that indicate it is a PEP405 virtual environment.
In the root directory for the virtual environment, the pyenv.cfg configuration file specifies different options for the virtual environment and its existence is an indicator that we are in the root folder for a virtual environment. In Linux and macOS, the folder will have the following main subfolders: bin, include, lib, lib/python3.6, and lib/python3.6/site-packages. In Windows, the folder will have the following main subfolders: Include, Lib, Lib\site-packages, and Scripts. The directory trees for the virtual environment in each platform are the same as the layout of the Python installation on these platforms.
The following diagram shows the folders and files in the directory trees generated for the 01 virtual environments in macOS and Linux platforms:
The following diagram shows the main folders in the directory trees generated for the virtual environment in Windows:
Now that we have created a virtual environment, we will run a platform-specific script to activate it. After we activate the virtual environment, we will install packages that will only be available in this virtual environment. This way, we will work with an isolated environment in which all the packages we install won't affect our main Python environment.
Note that the results of this command will be accurate if you don't start a different shell than the default shell in the terminal session. If you have doubts, check your terminal configuration and preferences. Run the following command in the Terminal in Linux or macOS:
echo $SHELL
The command will display the name of the shell you are using in the Terminal. In macOS, the default is /bin/bash and this means you are working with the bash shell. Depending on the shell, you must run a different command to activate the virtual environment in Linux or macOS.
If your Terminal is configured to use the bash shell in Linux or macOS, run the following command to activate the virtual environment. The command also works for the zsh shell:
source ~/HillarDjangoREST/01/bin/activate
If your Terminal is configured to use either the csh or tcsh shell, run the following command to activate the virtual environment:
source ~/HillarDjangoREST/01/bin/activate.csh
If your Terminal is configured to use the fish shell, run the following command to activate the virtual environment:
source ~/HillarDjangoREST/01/bin/activate.fish
After you activate the virtual environment, Command Prompt will display the virtual environment root folder name enclosed in parentheses as a prefix of the default prompt to remind us that we are working in the virtual environment. In this case, we will see (01) as a prefix for the Command Prompt because the root folder for the activated virtual environment is 01.
The following screenshot shows the virtual environment activated in a macOS Sierra Terminal with a bash shell, after executing the previously shown commands:
As we can see from the previous screenshot, the prompt changed from
Gastons-MacBook-Pro:~ gaston$ to (01) Gastons-MacBook-Pro:~ gaston$ after the activation of the virtual environment.
In Windows, you can run either a batch file in the Command Prompt or a Windows PowerShell script to activate the virtual environment.
If you prefer Command Prompt, run the following command in the Windows command line to activate the virtual environment:
%USERPROFILE%\HillarDjangoREST\01\Scripts\activate.bat
The following screenshot shows the virtual environment activated in Windows 10 Command Prompt, after executing the previously shown commands:
As we can see from the previous screenshot, the prompt changed from C:\Users\gaston to (01) C:\Users\gaston after the activation of the virtual environment.
If you prefer Windows PowerShell, launch it and run the following commands to activate the virtual environment. Note that you must have scripts execution enabled in Windows PowerShell to be able to run the script:
cd $env:USERPROFILE
HillarDjangoREST\01\Scripts\Activate.ps1
If you receive an error similar to the following lines, it means that you don't have scripts execution enabled:
C:\Users\gaston\HillarDjangoREST\01\Scripts\Activate.ps1 : File C:\Users\gaston\HillarDjangoREST\01\Scripts\Activate.ps1 cannot be loaded because running scripts is disabled on this system. For more information, see about_Execution_Policies at
http://go.microsoft.com/fwlink/?LinkID=135170.
At line:1 char:1
+ C:\Users\gaston\HillarDjangoREST\01\Scripts\Activate.ps1
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : SecurityError: (:) [], PSSecurityException
+ FullyQualifiedErrorId : UnauthorizedAccess
The Windows PowerShell default execution policy is Restricted. This policy allows the execution of individual commands but it doesn't run scripts. Thus, in case you want to work with Windows PowerShell, you will have to change the policy to allow the execution of scripts. It is very important to make sure that you understand the risks of the Windows PowerShell execution policies that allow you to run unsigned scripts. For more information about the different policies, check the following web page: https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_execution_policies?view=powershell-6.
The following screenshot shows the virtual environment activated in a Windows 10 PowerShell, after executing the previously shown commands:
It is extremely easy to deactivate a virtual environment generated by the previously explained process. The deactivation will remove all the changes made in the environment variables and will change the prompt back to its default message. Once you deactivate a virtual environment, you will go back to the default Python environment.
In macOS or Linux, just type deactivate and press Enter.
In a Windows Command Prompt, you have to run the deactivate.bat batch file included in the Scripts folder. In our example, the full path for this file is %USERPROFILE%\HillarDjangoREST\01\Scripts\deactivate.bat.
In Windows PowerShell, you have to run the Deactivate.ps1 script in the Scripts folder. In our example, the full path for this file is $env:userprofile\HillarDjangoREST\01\Scripts\Deactivate.ps1. Remember that you must have scripts execution enabled in Windows PowerShell to be able to run the script.
The instructions in the next sections assume that the virtual environment we have created is activated.
We have created and activated a lightweight virtual environment. It is time to run many commands that will be the same for either Linux, macOS, or Windows.
First, run the following command to install the Django web framework:
pip install django==1.11.5
The last lines of the output will indicate that the django package has been successfully installed. The process will also install the pytz package that provides world time zone definitions. Take into account that you may also see a notice to upgrade pip. The next lines show a sample of the four last lines of the output generated by a successful pip installation:
Collecting django
Collecting pytz (from django)
Installing collected packages: pytz, django
Successfully installed django-1.11.5 pytz-2017.2
Now that we have installed the Django web framework, we can install Django REST framework. Django REST framework works on top of Django and provides us with a powerful and flexible toolkit to build RESTful Web Services. We just need to run the following command to install this package:
pip install djangorestframework==3.6.4
The last lines for the output will indicate that the djangorestframework package has been successfully installed, as shown here:
Collecting djangorestframework
Installing collected packages: djangorestframework
Successfully installed djangorestframework-3.6.4
After following the previous steps, we will have Django REST framework 3.6.4 and Django 1.11.5 installed in our virtual environment. We will install additional packages as we need them in the forthcoming chapters.
Now, we will create our first app with Django and we will analyze the directory structure that Django creates. First, go to the root folder for the virtual environment: 01.
In Linux or macOS, enter the following command:
cd ~/HillarDjangoREST/01
If you prefer Command Prompt, run the following command in the Windows command line:
cd /d %USERPROFILE%\HillarDjangoREST\01
If you prefer Windows PowerShell, run the following command in Windows PowerShell:
cd /d $env:USERPROFILE\HillarDjangoREST\01
In Linux or macOS, run the following command to create a new Django project named restful01. The command won't produce any output:
python bin/django-admin.py startproject restful01
In Windows, in either Command Prompt or PowerShell, run the following command to create a new Django project named restful01. The command won't produce any output:
python Scripts\django-admin.py startproject restful01
The previous command creates a restful01 folder with other subfolders and Python files. Now, go to the recently created restful01 folder. Just execute the following command on any platform:
cd restful01
Then, run the following command to create a new Django app named toys within the restful01 Django project. The command won't produce any output:
python manage.py startapp toys
The previous command creates a new restful01/toys subfolder, with the following files:
views.py
tests.py
models.py
apps.py
admin.py
__init__.py
In addition, the restful01/toys folder will have a migrations subfolder with an __init__.py Python script. The following diagram shows the folders and files in the directory tree, starting at the restful01 folder with two subfolders - toys and restful01:
