官术网_书友最值得收藏!

Understanding the "Hello World" app

Given the environment set, what should we use to write our beautiful code? An editor or an IDE? If you're working on a low budget, try Light Table editor (http://lighttable.com/). Free, fast, and easy to use (Ctrl + Spacebar gives you access to all available options), it also has workspace support! Can't get any better for the money. If you're a lucky one with $200 to spare (or if you have a free license https://www.jetbrains.com/pycharm/buy/), just fork out for the PyCharm IDE which is pretty much the best IDE for Python Web development. Now let's move on.

Create a folder that will hold your project files (you don't need to but people will like you more if you do), as follows:

mkdir hello_world

Enter the new project folder and create the main.py file:

cd hello_world
touch main.py

The main.py file will have the whole "Hello World" application in it. Our main.py content should be like this:

# coding:utf-8
from flask import Flask
app = Flask(__name__)

@app.route("/")
def hello():
    return "Hello World!"

if __name__ == "__main__":
    app.run()
Tip

Downloading the example code

You can download the example code files for all Packt books you have purchased from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.

Wow! That took some typing, right? No? Yeah, I know. So, what did we just do?

The first line states that our main.py file should use utf-8 encoding. All the cool kids do that so don't be mean to your non-English pals and use that in all your Python files (doing so might help you avoid some nasty bugs in big projects).

In the second and third lines we import our Flask class and instantiate it. The name of our application is "app". Pretty much everything is related to it: views, blueprints, config, and so on. The argument, __name__ is required and is used to tell the application where to look for resources such as static content or templates.

In order to create our "Hello World", we need to tell our Flask instance how to respond when a user tries to access our Web application (using a browser or whatever). For that purpose, Flask has routes.

Routes are the way Flask reads a request header and decides which view should respond to that request. It does so by analyzing the path part of the requested URL and finding which route is registered with that path.

In the hello world example, in line 5, we use the route decorator to register the hello function to the path "/". Every time an app receives a request in which the path is "/", hello will respond to that request. The following snippet shows how to check the path part of a URL:

from urlparse import urlparse
parsed = urlparse("https://www.google.com/")
assert parsed.path == "/"

You could also have multiple routes mapped to the same function, like so:

@app.route("/")
@app.route("/index")
def hello():
    return "Hello World!"

In this case, both the "/" and "/index" paths would map to hello.

In lines 6 and 7 we have the function that will respond the request. Notice that it receives no parameters and responds –with a familiar string. It receives no parameters because the request data, like a submitted form, is accessed through a thread-safe variable called request that we will see more about in upcoming chapters.

With regard to the response, Flask can respond to requests in numerous formats. In our example, we respond with a plain string, but we could also respond with a JSON or HTML string.

Lines 9 and 10 are simple. They check whether main.py is being called as a script or as a module. If it is as a script, it will run the built-in development server that comes bundled with Flask. Let's try that:

python main.py

Your terminal console will output something like this:

Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)

Just open http://127.0.0.1:5000/ in your browser to see your app working.

Running main.py as a script is usually a very simple and handy setup. Usually, you have Flask-Script to handle calling the development server for you and other setups.

If you used main.py as a module, just import it as follows:

from main import what_I_want

You would usually do something like this to import an app factory function in your testing code.

That's pretty much all there is to know about our "Hello World" application. One thing our world application lacks is a fun factor. So let's add that; let's make your application fun! Maybe some HTML, CSS, and JavaScript could do the trick here. Let's try that!

主站蜘蛛池模板: 和田县| 德庆县| 平山县| 晋江市| 平谷区| 许昌市| 昭觉县| 葵青区| 突泉县| 文安县| 泉州市| 庆元县| 余干县| 万荣县| 杨浦区| 沽源县| 遵化市| 温泉县| 黎平县| 濮阳县| 鄂伦春自治旗| 双流县| 鹰潭市| 四子王旗| 乾安县| 吴忠市| 昭平县| 江源县| 连城县| 绍兴市| 尼木县| 泰顺县| 江津市| 罗城| 定陶县| 张北县| 宣恩县| 隆德县| 安泽县| 沾化县| 甘洛县|