Flask framework learning notes (1) installation (windows Installation and centos installation)

Source: Internet
Author: User

Flask depends on two external libraries: Werkzeug and Jinja2. Werkzeug is a WSGI (standard Python interface developed and deployed between web applications and multiple servers) tool set. Jinja2 is responsible for rendering templates.

I. Installation

Prerequisites for Flask Installation

1. Version python2.x has been installed.

2. easy_install is installed.

Before installing flask, you must first install python and easy_install. easy_install only supports pyhon2.x and does not support python3.x. Therefore, you 'd better choose python2.x when installing python. Here is 2.7.

The installation of python2.7 is very simple. There are many articles on this site, which are not described here. You can add environment variables after installation is complete.

Win7:

Configure Environment Variables

Method 1: (Computer> Properties> advanced system Settings> environment variables> python installation path)

Method 2: Run cmd

Set: set PYTHONPATH = % PYTHONPATH %; C: \ My_python_lib

View: echo % PATH %

Install easy_install:

: Http://pypi.python.org/pypi/setuptools

In windows, only one ez_setup.py script is available. Download the script and run it in the Directory D: \ Python \ python2.7. easy_install is automatically installed in the Directory D: \ Python \ python2.7 \ Scripts.

Easy_install add environment variable: Path: D: \ Python \ python2.7 \ Scripts

Install flask after the two are installed.

Install virtualenv, which is mainly used to isolate the interpreter environment and avoid library dependencies of multiple python or multiple python on the same machine.

Then configure the Virtual Environment

Then cd to the Scripts in the myvir directory

Enter activate. bat to enter the virtual environment, and then enter easy_install Flask to install

Test result: whether the installation is successful:

In pycharmsoftware, create a flaskproject and then select python.exe in myvirto run the script.

Create a simple hello world script named test1.py:

from flask import Flaskapp=Flask(__name__)@app.route('/')def hello_world():return "Hello World~~~"if __name__ == '__main__':app.run()

Click Run to display

You can access it through the given URL. Note: The port is always running. to close the port after completion, click Run-> stop in pycharm.
By default, only local access is allowed, and port 5000 is used.

The last line is changed to app. run ('0. 0.0.0 ', 12345), so that other users can access it.

Resolution:

from flask import Flask

Import Flask class

app = Flask(__name__)

Instantiate the object app. The parameter is the name of the application module or package. Here _ name _ refers to the _ main program. This parameter is required, so that Flask can know where to find it.

To templates and static files.

@ App. route ("/")

Use the route () decorator to tell Flask the URL of the function to be triggered. It can be customized, for example, @ app. route ("/test1.py"). The file name will be followed during access.

def hello():    return "Hello World!"

The defined function is used to generate the associated URL and return the information that needs to be displayed in the user's browser.

App. run ()

After running the server application, only local access is allowed by default. If you need other connections, you can specify the host, for example, app. run (host = '0. 0.0.0 ')

The default port is 5000. You can use the custom host and port: app. run (host = "0.0.0.0", port = 8000)

Externally accessible server

If you run the server, you will notice that it can only be accessed from your own computer, and no other part of the network can be accessed. This is by default, because in debugging mode, you can execute any Python code on your computer.

If you disable debug or trust users in your network, you can simply modify the run () method to make your server public available, as shown below:

App. run (host = '0. 0.0.0 ')

This allows the operating system to listen to all public IP addresses.

Ii. Install Version 3.3 in windows:

NOTE: If 2.7 is installed by default and you want to install 3.3, you must enter the 3.3 installation directory and run python ez_setup.py (ez_setup.py: https://pypi.python.org/pypi/setuptools ).

Go to the generated scripts directory and run the following command to install virtualenv.

Similarly, virtualenv of 3.3 is used when a virtual environment is created. Otherwise, an error is returned.

Then cd to the Scripts in the myvir directory

Enter activate. bat to enter the virtual environment, and then enter easy_install Flask to install

3. Install the flask framework of python2.6 in centos6.4 ::

Install and execute the command:

Yum install openssh-serverpython -- version (check whether the version is correct) yum install python-setuptoolseasy_install virtualenv (easy_install2.6 is installed by default) virtualenv

After the installation is complete, you can immediately open the shell and create your own environment.

1. Global (not recommended ):

Easy_install Flask global installation. The local installation method is as follows.

Test code:

from flask import Flask app = Flask(__name__) @app.route('/') def hello_world(): return "Hello World!" if __name__ == '__main__': app.run(host='0.0.0.0') 

There is no requirement on the location where the file is stored. It can be executed anywhere. (Global installation)
Access from another server: http: // IP: 5000
Then, for example, template rendering, you only need to create a templates folder in your project.

2. Local Environment:

I usually create a project folder and create a venv folder under it

[Root @ localhost opt] # mkdir myweb [root @ localhost opt] # cd myweb [root @ localhost myweb] # virtualenv venv (Note: The venv directory name is set here) new python executable in venv/bin/pythonInstalling setuptools, pip... done.

Now, whenever you want to work on a project, you only need to activate the corresponding environment.

Benefits:

Everything has been installed in this virtual environment, so your main Python installation environment will not be affected (it can support the use of several environments at the same time ). The additional advantage is that you do not need the root administrator privilege to install the SDK in this way.
After the migration, the execution file cannot be used because the path is changed. You still need to re-build the environment.

On OS X and Linux, perform the following operations:

[Root @ localhost venv] #. bin/activate # activation (activated every time running) (venv) [root @ localhost venv] #

The following operations apply to Windows:

$ Venv \ scripts \ activate

Either way, you should have activated virtualenv now (note that your shell prompt displays the active environment ).

Now you only need to enter the following command to activate Flask in virtualenv:

(Venv) [root @ localhost venv] # pip install Flask # You only need to start executing once... Successfully installed Flask Werkzeug Jinja2 itsdangerous markupsafeCleaning up...

After a few seconds, everything is done.
An error may occur:

SSLError: The read operation timed out

Storing debug log for failure in/root/. pip/pip. log

If this error occurs, you only need to re-execute the command.

Execute. activate. csh to exit virtualenv (I don't know if it is the correct method, but it can exit)

4. Install the flask framework of python3.3 in centos:

If easy_install 3.3 is used:

[Root @ localhost python3.3.3] # wget extends python3.3.3] # python3.3 ez_setup.py (you must specify the 3.3 execution file. Otherwise, the default python is used.) [root @ localhost python3.3.3] # easy_install

Now you can see the version.

Easy_install easy_install-2.6 easy_install-3.3

The subsequent installation steps are the same as those in step 2.6, but you must specify the command (3.3 or 2.6) during installation)
After the installation is complete, both versions have their own virtual environment and execute scripts in the environment.
The installation was successful before, and an error was reported when it was installed on another server:

[root@www python3.3]# python3.3 ez_setup.py Extracting in /tmp/tmpj462kbTraceback (most recent call last): File "ez_setup.py", line 332, in <module>  sys.exit(main()) File "ez_setup.py", line 329, in main  return _install(archive, _build_install_args(options)) File "ez_setup.py", line 51, in _install  with archive_context(archive_filename): File "/usr/local/python3.3/lib/python3.3/contextlib.py", line 48, in __enter__  return next(self.gen) File "ez_setup.py", line 101, in archive_context  archive.extractall() File "/usr/local/python3.3/lib/python3.3/zipfile.py", line 1232, in extractall  self.extract(zipinfo, path, pwd) File "/usr/local/python3.3/lib/python3.3/zipfile.py", line 1220, in extract  return self._extract_member(member, path, pwd) File "/usr/local/python3.3/lib/python3.3/zipfile.py", line 1282, in _extract_member  with self.open(member, pwd=pwd) as source, \ File "/usr/local/python3.3/lib/python3.3/zipfile.py", line 1202, in open  close_fileobj=not self._filePassed) File "/usr/local/python3.3/lib/python3.3/zipfile.py", line 649, in __init__  self._decompressor = _get_decompressor(self._compress_type) File "/usr/local/python3.3/lib/python3.3/zipfile.py", line 612, in _get_decompressor  return zlib.decompressobj(-15)AttributeError: 'NoneType' object has no attribute 'decompressobj'[root@www python3.3]# 

Related modules are missing:
The solution is as follows:

yum install build-essential libssl-dev libxml2-dev libbz2-dev libjpeg62-dev libreadline5-dev wv poppler-utils zlib1g zlib1g-dev zlibc libghc6-zlib-dev zlibc

However, if I reinstall python once again, it will be okay.

However, problems occur when you install virtualenv:

[root@www python3.3]# easy_install-3.3 virtualenvSearching for virtualenvReading https://pypi.python.org/simple/virtualenv/Download error on https://pypi.python.org/simple/virtualenv/: unknown url type: https -- Some packages may not be found!Couldn't find index page for 'virtualenv' (maybe misspelled?)Scanning index of all packages (this may take a while)Reading https://pypi.python.org/simple/Download error on https://pypi.python.org/simple/: unknown url type: https -- Some packages may not be found!No local packages or download links found for virtualenverror: Could not find suitable distribution for Requirement.parse('virtualenv')[root@www python3.3]#

Then directly find the prompt path (https://pypi.python.org/simple/virtualenv/) download, you can also install:

[root@www python3.3]# wget https://pypi.python.org/packages/source/v/virtualenv/virtualenv-1.9.tar.gz#md5=e03b76752b8ce7eee67c6298414cac79[root@www python3.3]# lsbin ez_setup.py include lib setuptools-5.2.zip share virtualenv-1.9.tar.gz[root@www python3.3]# easy_install-3.3 virtualenv-1.9.tar.gzProcessing virtualenv-1.9.tar.gzWriting /tmp/easy_install-quwwll/virtualenv-1.9/setup.cfgRunning virtualenv-1.9/setup.py -q bdist_egg --dist-dir /tmp/easy_install-quwwll/virtualenv-1.9/egg-dist-tmp-xhue8rwarning: no previously-included files matching '*' found under directory 'docs/_templates'warning: no previously-included files matching '*' found under directory 'docs/_build'Adding virtualenv 1.9 to easy-install.pth fileInstalling virtualenv script to /usr/local/python3.3/binInstalling virtualenv-3.3 script to /usr/local/python3.3/binInstalled /usr/local/python3.3/lib/python3.3/site-packages/virtualenv-1.9-py3.3.eggProcessing dependencies for virtualenv==1.9Finished processing dependencies for virtualenv==1.9[root@www python3.3]# vivi       vigr      virtualenv   virtualenv-3.3view      vipw      virtualenv-2.6 visudo

Problems Occurred When installing Flask:

AttributeError: 'module' object has no attribute 'httpsconnection'

In the final analysis, python is not properly installed, and some modules are missing. Therefore, be sure to reinstall it if it is not installed.
Install all Development Kits before installing python

[root@lujie ~]# yum groupinstall "Development tools"[root@lujie ~]#yum install zlib-devel bzip2-devel openssl-devel ncurses-devel

V. Installation Summary:

What is the difference between easy_install virtualenv and pip install virtualenv?
The role of easy_insall is similar to that of cpan in perl and gem in ruby. It provides an easy way to install modules online with one click. pip is an easy version of easy_install and provides better prompt information, delete a package. In earlier versions of python, only easy_install and pip are supported.
Easy_install usage:

1) install a package

$ easy_install <package_name>$ easy_install "<package_name>==<version>"

2) upgrade a package

$ easy_install -U "<package_name>>=<version>"

Pip usage

1) install a package

$ pip install <package_name>$ pip install <package_name>==<version>

2) upgrade a package (if no version number is provided, upgrade to the latest version)

$ pip install --upgrade <package_name>>=<version>

3) delete a package

$ pip uninstall <package_name>

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.