How to deploy a Python Web application: record a complete Heroku deployment process

Source: Internet
Author: User
Tags postgres database subdomain name heroku toolbelt

How to deploy a Python Web application: record a complete Heroku deployment process

0. Select Heroku Cloud Platform

With the wave of cloud computing, the domestic cloud services can be described as diverse, although the price is not high, but can truly provide permanent free use, even if there are some restrictions, it does not seem to find.

To meet the requirements of learning, research, experiment, test, and real application, we may wish to deploy the application on the Heroku cloud platform outside China, in addition to the ipvs database provided by Heroku, the free version of Heroku can be added to its own Web application without paying for small databases with less than 10 thousand records, this is definitely the best choice.

In addition, Heroku has excellent support for Python, so it is much easier to deploy it, saving a lot of unnecessary trouble.

I want to deploy the application on Heroku recently. Here I will share the complete deployment process with you.

Note: the operating system I use is Ubuntu 15.10. The Python Web application deployed is a Flask-based application. The following deployment process is deployed in this operating environment, we recommend that you deploy the service in Linux. (Of course, it would be better if you have a Mac Book, but the blogger has no money and can't afford it)

1. Prepare the Git Environment

If you want to use Heroku, your Web application must be hosted in the Git repository. If you have been using Git for development, the problem can be easily solved, I believe you understand the truth. If not, use the following method to generate a Git repository, which is very simple.

Many people think it is very troublesome to use Git, so they gave up the use of the Heroku platform, which is a great waste:

1. The first waste is a good platform resource such as Heroku;

2. Then, I gave up using Git as an excellent version control system.

3. In addition, the Linux environment is abandoned.

In fact, these are very helpful for development! So don't worry about it. As long as you are not fully engaged in Windows platform development in the future, you should understand this. As long as you get used to it slowly, everything will be very natural in the future.

Step 1: Install Git

Take Ubuntu as an example. You can directly install it using the following command:

sudoapt-getinstallgit

Of course, if you are using another version of Linux, it is not difficult to install it.

Step 2: Put your complete Web application in a new directory

For example, I have developed a complete Web application, which mainly includes the following files and applications:

Drwxrwxr-x6xpleafxpleaf4096 August 16: 04. drwxr-xr-x38xpleafxpleaf4096 August 16: 01 .. drwxrwxr-x7xpleafxpleaf4096 August 03: 31app-rw-rw-r -- 1xpleafxpleaf3295 August 03: 31config. py-rw-r -- 1xpleafxpleaf1083 August 03: 31LICENSE-rwxrwxr-x1xpleafxpleaf239 August 03: 31manage. pydrwxrwxr-x3xpleafxpleaf4096 August 03: 31migrations-rw-rw-r -- 1xpleafxpleaf25 August 03: 13procfile-rw-r -- 1xpleafxpleaf376 August 03: 31README. md-rw-r -- 1xpleafxpleaf76 August 03: 13requirements.txt drwxrwxr-x2xpleafxpleaf4096 August 03: 31 tests

Create a folder named Heroku_pro and put the complete Web application above, as shown below:

xpleaf@leaf:~/Heroku_pro$pwd/home/xpleaf/Heroku_proxpleaf@leaf:~/Heroku_pro$lsappconfig.pyLICENSEmanage.pymigrationsREADME.mdrequirements.txttestsProcfile

This step is complete!

Step 3: generate a Git repository under the Heroku_pro directory

Xpleaf @ leaf :~ /Heroku_pro $ gitinit initializes the empty Git version library at/home/xpleaf/Heroku_pro/. git/

At this time, you will find an additional. git directory under the current directory:

xpleaf@leaf:~/Heroku_pro$ls-a.app.gitmanage.pyREADME.mdtests..config.pyLICENSEmigrationsrequirements

This step is complete.

Step 4: host all the files in the current directory to the local Git Repository

Xpleaf @ leaf :~ /Heroku_pro $ gitadd. xpleaf @ leaf :~ /Heroku_pro $ gitcommit-m "ver1.0" [master (root commit) a7cea3f] ver1.078fileschanged, 3350 insertions (+) createmode100644LICENSEcreatemode100644README. mdcreatemode100644app/_ init __. pycreatemode100644app/api_defaults 0/_ init __. pycreatemode100644app/api_00000/authentication. py ......

OK. This step is complete.

The use of Git is clearly not the focus of the discussion here, but it is just a temporary solution for friends who have not used Git.

2. Register a Heroku account

Like most cloud platforms in China, you need to register an account first. You can register an account at the following link:

Https://www.heroku.com/

 

3. Install the Heroku Toolbelt Client

Toolbelt is the command line tool of Heroku. The advantage of using this client is that we can manage our Web applications hosted on Heroku locally through command line operations.

Take Ubuntu as an example. Refer to the official installation documentation:

We can use the following command for installation:

wget-O-https://toolbelt.heroku.com/install-ubuntu.sh|sh

See the official documentation here: https://toolbelt.heroku.com/

4. log on to Heroku

Run the following command in the Heroku_pro directory and log on to Heroku:

xpleaf@leaf:~/Heroku_pro$herokuloginEnteryourHerokucredentials.Email:[email protected]Password(typingwillbehidden):[email protected]xpleaf@leaf:~/Heroku_pro$

Note the prompt after successful login:Logged in as [email protected]

Note that by default, the login command automatically creates an SSH Public Key for your current host and uploads it. The SSH Public Key is very important and must be used when you execute the git push command later, but don't worry, the heroku client will automatically help us deal with it. You can also manually upload the file by executing the command heroku keys: add.

5. Use the Heroku client to create an app

The so-called app is actually a subdomain name of herokuapp.com. If you create an app named my-Heroku-app-cn in heroku, you can directly use the addressHttps: // my-HerOku-app-cn.herokuapp.comTo access your Web application. Therefore, you must note that you cannot use any Web application that has been used by others. Let's create one.

xpleaf@leaf:~/Heroku_pro$herokucreatemy-heroku-app-cnCreatingmy-heroku-app-cn...done,stackiscedar-14https://my-heroku-app-cn.herokuapp.com/|https://git.heroku.com/my-heroku-app-cn.git

The above prompt indicates that the program is successfully created! Heroku also assigned us a Git server address for https://git.heroku.com/my-heroku-app-cn.git

Of course, the app name can also be changed. You only need to log on to the official website and modify it on your personal information page.

6. Configure the database

Heroku supports ipvs databases in an extended way, but there are some restrictions, as mentioned above. Here we will use the Postgres database, which also means that you need to add the corresponding database path in your Web application source code, which will be discussed later.

Run the following command to configure the database:

xpleaf@leaf:~/Heroku_pro$herokuaddons:createheroku-postgresql:hobby-devCreatingpostgresql-rectangular-17531...done,(free)Addingpostgresql-rectangular-17531tomy-heroku-app-cn...doneSettingDATABASE_URLandrestartingmy-heroku-app-cn...done,v3Databasehasbeencreatedandisavailable!Thisdatabaseisempty.Ifupgrading,youcantransfer!datafromanotherdatabasewithpg:copyUse`herokuaddons:docsheroku-postgresql`toviewdocumentation.

The above prompt indicates that the database has been configured successfully. For details about the database, you can also go to the personal center on the official website to view the details, as shown below:

Here we need to pay attention to one sentence:Setting DATABASE_URL and restarting my-heroku-app-cn... done, v3

That is to say, Heroku automatically createsMy-heroku-app-cnThe program createsDATABASE_URLEnvironment variable. The value of the variable is the path address of the database on the Heroku platform. This also means that if you want your Web application to be successfully deployed, you can connect to the database normally, you must set the database address to DATABASE_URL in your source code. That's all. Other Heroku will be done for us, so don't worry.

7. Configure necessary environment variables

This is not necessary. It depends on whether the source code of your Web application needs to obtain the system environment variables. If so, you can set the environment variables in the following ways.

For example, I have the following two lines of code in my source code configuration file:

MAIL_USERNAME=os.environ.get('MAIL_USERNAME')MAIL_PASSWORD=os.environ.get('MAIL_PASSWORD')

Obviously, the user name and password of the email should not be in the source code, so I know the user name and password by obtaining the value of the environment variable, therefore, I need to set the corresponding environment variables on Heroku. The command is as follows:

xpleaf@leaf:~/Heroku_pro$herokuconfig:setMAIL_USERNAME="xpleaf"Settingconfigvarsandrestartingmy-heroku-app-cn...doneMAIL_USERNAME:xpleafxpleaf@leaf:~/Heroku_pro$herokuconfig:setMAIL_PASSWORD="***"Settingconfigvarsandrestartingmy-heroku-app-cn...doneMAIL_PASSWORD:***

Of course, if you need to set other environment variables, you can set them in this way.

8. Use production Web Servers

We know thatDjangoOrFlaskDuring development, they all come with development Web servers to connect to our Web applications, which is not suitable for the development process. However, what we need to do now is to deploy ourWeb ApplicationsTherefore, you cannot say that you still use the development servers that come with these Web frameworks, because the performance is not guaranteed because they are all Web servers designed for the development environment, rather than for the production environment. Therefore, we need to use the production environmentWeb Server. (PS: Please noteWeb ApplicationsAndWeb Server)

The Web application I want to deploy is based on Flask, so of course I need to use a Web server software that supports Flask. Here I am using Gunicorn. Of course, this depends on what Web framework you are using. You can learn about this.

I chose to use Gunicorn as my production environment. I just need to add it to the dependency file.

Of course, you can also download Gunicorn for local testing, because not everyone uses the Python Web framework Flask or Gunicorn as the Web server software, so it is not mentioned here.

9. Add dependency requirement files and Profile files

This is required and very important, otherwise it will be difficult to deploy it!

Heroku requires that the following two files be included in the directory of our Web program (the Web application for Python here:

Required file Description
Requirements.txt Various third-party extension packages on which Web applications depend
Procfile It contains the commands executed by my Web application server at startup.

As you can see in my Heroku_pro directory:

Xpleaf @ leaf :~ /Heroku_pro1_ls-lrequirements.txt Procfile-rw-r -- 1xpleafxpleaf25 January 29 03: 13Procfile-rw-rw-r -- 1xpleafxpleaf76 January 29 03: 13requirements.txt

Note that these two files must be located in the current Heroku_pro directory.

The content of the requirements.txt file is similar to the following:

Flask==0.10.1Flask-Bootstrap==3.0.3.1Flask-HTTPAuth==2.7.0Flask-Login==0.3.1...SQLAlchemy==0.9.9WTForms==1.0.5Werkzeug==0.10.4alembic==0.6.2bleach==1.4.0

It contains various extension packages that support the running of my Web applications. Of course, what the content is depends on the Web project you are developing.

The content of the Profile file is similar to the following:

web:gunicornmanage:app

As mentioned above, commands are put in it. For example, the command here is used to start the Gunicorn production environment Web server that I mentioned earlier.

Note that these two files are very important. If they are not, they will fail to be deployed soon.

10. Execute git push for deployment

After the preceding confirmation is correct, you can deploy it. Of course, if you temporarily modify the files in your current Heroku_pro directory, use the following command to submit your modifications:

gitadd.gitcommit-m"ver1.0"

OK. The deployment will start as follows:

Xpleaf @ leaf :~ /Heroku_pro $ gitpushherokumaster object count: 97, complete. deltacompressionusingupto4threads. in the compressed object: 100% (90/90), complete. write object: 100% (97/97), 35.04KiB | 0 bytes/s, complete. total97 (delta22), reused0 (delta0) remote: Compressingsourcefiles... done. remote: Buildingsource: remote: -----> Pythonappdetectedremote: -----> Installingruntime (python-2.7.11) remote: -----> Installingdependencieswithpipremote: collectingFlask = 0.10.1 (from-rrequirements/common.txt (line1 )).......... remote: -----> Preparingstaticassetsremote: Collectstaticconfigurationerror. todebug, run: remote: $ herokurunpythonmanage. pycollectstatic -- noinputremote: remote: -----> Discoveringprocesstypesremote: Procfiledeclarestypes-> webremote: remote: -----> Compressing... remote: Done: 37.2 Mremote: -----> Launching... remote: Releasedv6remote: slave-> master

There is a lot of output information in the middle. This is what Heroku needs to install for our environment, which is previously specified in the requirement file. Of course, these operations are all performed in Heroku, and we only see an operation process of it locally.

After the deployment is complete, start the Web Server Based on the startup method selected by my Flask application by running the following command:

# Start the Web server and perform Initialization Configuration xpleaf @ leaf :~ /Heroku_pro $ herokurunpythonmanage. pydeployRunningpythonmanage. pydeployonmy-heroku-app-cn... up, run.7690INFO [alembic. migration] ContextimplSQLiteImpl ....... INFO [alembic. migration] Runningupgrade288cd3dc5a8-> 2356a38169ea, followersINFO [alembic. migration] Runningupgrade2356a38169ea-> 51f5ccfba190, comments # restart xpleaf @ leaf :~ /Heroku_pro $ herokurestartRestartingdynos... done

After completing the preceding steps, you can access the Web application we created:

Https://my-heroku-app-cn.herokuapp.com/

Of course, when you access it, I may have turned it off. You can access the address of another application deployed in the same way:

Https://flasky-mini.herokuapp.com/

11. Upgrade

If you need to modify your source code to add or delete some functions, after modifying them in the Heroku_pro directory, execute the following commands in sequence:

# Tell Heroku that you want to upgrade herokumaintenance: on # submit and deploy gitpushherokumaster # re-run the server herokurunpythonmanage. pydeployherokurestart # Tell Heroku that the maintenance is off

Okay. Now, this article is over. In fact, whether your Web application is developed based on Python or other languages, deploying the application to Heroku is similar, but here we focus on Python Web applications.

Of course, you may encounter various problems in the actual deployment process. In this case, you need to make full use of your random response capability. When a problem occurs, you can search by Google (Baidu has very few materials, so you can find a solution if Google doesn't get it), or search for or ask a question on Stack Overflow, at the same time, read the official documents according to the error message to solve the problem.

However, in any case, the main process for deploying a Python Web application is similar to the operation shown above. I believe this article will be helpful to my friends who first deployed a Python Web application on Heroku, it is indeed hoped to help more friends, because there are not many domestic Python Web deployment resources, let alone the deployment to foreign cloud platforms.

Well, I hope to help anyone in need. Thank you!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.