














Studirajte zahvaljujući brojnim resursima koji su dostupni na Docsity-u
Zaradite bodove pomažući drugim studentima ili ih kupite uz Premium plan
Ova stranica nije vidljiva u pregledu
Ne propustite važne delove!















In the previous chapter, you created a RESTful API for your project. In this chapter, you will learn how to do the following:
It's time to deploy your Django project in a production environment. We are going to follow the next steps to get our project live:
In real world projects, you will have to deal with multiple environments. You will have at least a local and a production environment, but there might be other environments as well. Some project settings will be common to all environments, but others will have to be overridden per environment. Let's set up project settings for multiple environments, while keeping everything neatly organized.
Going Live Create a settings/ directory inside your main educa project directory. Rename the settings.py file of your project to settings/base.py and create the following additional files so that the new directory looks like this: settings/ init.py base.py local.py pro.py These files are as follows:
Going Live When handling multiple environments, create a base settings file, and a settings file for each environment. Environment settings files should inherit the common settings and override environment specific settings. We have placed the project settings in a different location from the default settings. py file. You will not be able to execute any commands with the manage.py tool unless you specify the settings module to use. You will need to add a --settings flag when you run management commands from the shell or set a DJANGO_SETTINGS_MODULE environment variable. Open the shell and run the following command: export DJANGO_SETTINGS_MODULE=educa.settings.pro This will set the DJANGO_SETTINGS_MODULE environment variable for the current shell session. If you want to avoid executing this command for each new shell, add this command to your shell's configuration in the .bashrc or .bash_profile file. If you don't set this variable, you will have to run management commands, including the --settings flag. For example: python manage.py migrate –-settings=educa.settings.pro You have now successfully organized settings for multiple environments.
Throughout this book we have been using the SQLite database. This is simple and quick to setup, but for a production environment you will need a more powerful database like PostgreSQL, MySQL, or Oracle. We are going to use PostgreSQL for our production environment. PostgreSQL is the recommended database for Django because of the features and performance it offers. Django also comes with the django.contrib.postgres package that allows you to take advantage of specific PostgreSQL features. You can find more information about this module at https:// docs.djangoproject.com/en/1.8/ref/contrib/postgres/. If you are using Linux, install the dependencies for PostgreSQL to work with Python like this: sudo apt-get install libpq-dev python-dev Then install PostgreSQL with the following command: sudo apt-get install postgresql postgresql-contrib If you are using Mac OS X or Windows, you can download PostgreSQL from http://www.postgresql.org/download/.
Chapter 13 Let's create a PostgreSQL user. Open the shell and run the following commands: su postgres createuser -dP educa You will be prompted for a password and permissions you want to give to this user. Enter the desired password and permissions and then create a new database with the following command: createdb -E utf8 -U educa educa Then edit the settings/pro.py file and modify the DATABASES setting to make it look as follows: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'educa', 'USER': 'educa', 'PASSWORD': '*****', } } Replace the preceding data with the database name and credentials for the user you created. The new database is empty. Run the following command to apply all database migrations: python manage.py migrate Finally, create a superuser with the following command: python manage.py createsuperuser
Django includes the check management command to check your project anytime. This command inspects the apps installed in your Django project and outputs any errors or warnings. If you include the --deploy option, additional checks only relevant for production use will be triggered. Open the shell and run the following command to perform a check: python manage.py check --deploy
Chapter 13
You can run uWSGI from the command line. Open the shell and run the following command from the educa project directory: uwsgi --module=educa.wsgi:application --env=DJANGO_SETTINGS_MODULE=educa.settings.pro --http=127.0.0.1:80 --uid=1000 --virtualenv=/home/zenx/env/educa/ You might have to prepend sudo to this command if you don't have the required permissions. With this command, we run uWSGI on our localhost with the following options:
projectname = educa base = /home/zenx/educa
master = true virtualenv = /home/zenx/env/%(projectname)
Going Live pythonpath = %(base) chdir = %(base) env = DJANGO_SETTINGS_MODULE=%(projectname).settings.pro module = educa.wsgi:application socket = /tmp/%(projectname).sock We define the following variables:
Going Live
Create a new file inside the config/ directory and name it nginx.conf. Add the following code to it:
upstream educa { server unix:///tmp/educa.sock; } server { listen 80; server_name www.educaproject.com educaproject.com; location / { include /etc/nginx/uwsgi_params; uwsgi_pass educa; } } This is the basic configuration for Nginx. We set up an upstream named educa, which points to the socket created by uWSGI. We use the server directive and add the following configuration:
Chapter 13 Open a second shell and run Nginx with the command: service nginx start Since we are using a sample domain name, we need to redirect it to our local host. Edit your /etc/hosts file and add the following lines to it: 127.0.0.1 educaproject.com 127.0.0.1 www.educaproject.com By doing so, we are routing both hostnames to our local server. In a production server, you won't need to do this since you will point your hostname to your server in your domain's DNS configuration. Open http://educaproject.com/ in your browser. You should be able to see your site, still without any static assets being loaded. Our production environment is almost ready.
For the best performance, we are going to serve static assets directly with Nginx. Edit the settings/base.py file and add the following code to it: STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static/') We need to export static assets with Django. The collectstatic command copies static files from all applications and stores them in the STATIC_ROOT directory. Open the shell and run the following command: python manage.py collectstatic You will see the following output: You have requested to collect static files at the destination location as specified in your settings: /educa/static This will overwrite existing files! Are you sure you want to do this? Enter yes so that Django copies all files. You will see the following output: 78 static files copied to /educa/static
Chapter 13 You can fill in the requested data with your own information. The most important field is the Common Name. You have to specify the domain name for the certificate. We will use educaproject.com. This will generate, inside the ssl/ directory, an educa.key private key file and an educa.crt file, which is the actual certificate.
Edit the nginx.conf file and modify the server directive to include the following SSL directives: server { listen 80; listen 443 ssl; ssl_certificate /home/zenx/educa/ssl/educa.crt; ssl_certificate_key /home/zenx/educa/ssl/educa.key; server_name www.educaproject.com educaproject.com;
} Our server now listens both to HTTP through port 80 and HTTPS through port 443. We indicate the path to the SSL certificate with ssl_certificate and the certificate key with ssl_certificate_key. Restart Nginx with the following command: sudo service nginx restart Nginx will load the new configuration. Open https://educaproject.com/ with your browser. You should see a warning message similar to the following one:
Going Live The message might be different depending on your browser. It alerts you that your site is not using a trusted certificate; the browser cannot verify the identity of your site. This is because we signed our own certificate instead of obtaining one from a trusted Certification Authority. When you own a real domain you can apply for a trusted CA to issue an SSL certificate for it, so that browsers can verify its identity. If you want to obtain a trusted certificate for a real domain, you can refer to the Let's Encrypt project created by the Linux Foundation. It is a collaborative project which aims to simplify obtaining and renewing trusted SSL certificates for free. You can find more information at https://letsencrypt.org/. Click the Add Exception button to let your browser know that you trust this certificate. You will see that the browser displays a lock icon next to the URL, as shown in the following screenshot: If you click the lock icon, the SSL certificate details will be displayed.
Django includes some settings specific to SSL. Edit the settings/pro.py settings file and add the following code to it: SECURE_SSL_REDIRECT = True CSRF_COOKIE_SECURE = True These settings are as follows:
Going Live During the request phase, the following methods of the middleware are executed:
Chapter 13
Middleware can reside anywhere within your project. However, it's recommended to create a middleware.py file in your application directory. Create a new file inside the courses application directory and name it middleware.py. Add the following code to it: from django.core.urlresolvers import reverse from django.shortcuts import get_object_or_404, redirect from .models import Course class SubdomainCourseMiddleware(object): """ Provides subdomains for courses """ def process_request(self, request): host_parts = request.get_host().split('.') if len(host_parts) > 2 and host_parts[0] != 'www':
course = get_object_or_404(Course, slug=host_parts[0]) course_url = reverse('course_detail', args=[course.slug])
url = '{}://{}{}'.format(request.scheme, '.'.join(host_parts[1:]), course_url) return redirect(url) We create a custom middleware that implements process_request(). When a HTTP request is received, we perform the following tasks:
Chapter 13 A management command consists of a Python module containing a Command class that inherits from django.core.management.BaseCommand. You can create simple commands, or make them take positional and optional arguments as input. Django looks for management commands in the management/commands/ directory for each active application in the INSTALLED_APPS setting. Each module found is registered as a management command named after it. You can learn more about custom management commands at https://docs. djangoproject.com/en/1.8/howto/custom-management-commands/. We are going to create a custom management command to remind students to enroll at least in one course. The command will send an e-mail reminder to users that have been registered longer than a specified period, but are not enrolled in any course yet. Create the following file structure inside the students application directory: management/ init.py commands/ init.py enroll_reminder.py Edit the enroll_reminder.py file and add the following code to it: import datetime from django.conf import settings from django.core.management.base import BaseCommand from django.core.mail import send_mass_mail from django.contrib.auth.models import User from django.db.models import Count class Command(BaseCommand): help = 'Sends an e-mail reminder to users registered more than N days that are not enrolled into any courses yet' def add_arguments(self, parser): parser.add_argument('--days', dest='days', type=int) def handle(self, *args, **options): emails = [] subject = 'Enroll in a course' date_joined = datetime.date.today() - datetime. timedelta(days=options['days'])
Going Live users = User.objects.annotate(course_count=Count('courses_ enrolled')).filter(course_count=0, date_joined__lte=date_joined) for user in users: message = 'Dear {},\n\nWe noticed that you didn't enroll in any courses yet. What are you waiting for?'.format(user.first_name) emails.append((subject, message, settings.DEFAULT_FROM_EMAIL, [user.email])) send_mass_mail(emails) self.stdout.write('Sent {} reminders' % len(emails)) This is our enroll_reminder command. The preceding code is as follows: