FLASK-web框架

基于Python的Web开发 Flask

       使用Flask进行Web开发:

一,一个最小的WEB结构

       

[python]  view plain  copy
  1. from flask import Flask  
  2. webapp =Flask(__name__)  
  3. webapp.run()  

是的,它已经可以运行了,默认运行在127.0.0.1:5000

二,项目确实是成功运行了,但是它没有任何可以访问的页面,现在就为它添加一个主页:

[python]  view plain  copy
  1. @app.route('/'#路由  
  2. def index(): #视图函数  
  3.     return ''''' 
  4.    <html> 
  5.        <head>index</head> 
  6.        <body> 
  7.            <p>Welcome!</p> 
  8.        </body> 
  9. </html>'''  

这样我们访问http://127.0.0.1:5000/的时候就会返回一个head为index,body里只有一个p标签内容为Welcome的页面。

三,虽然我们有了页面,但是一千个页面就需要一千个视图函数,这样太不人性化了

[python]  view plain  copy
  1. @app.route('/info/<info>')#路由  
  2. defindex(info): #视图函数  
  3.     return ''''' 
  4.     <html> 
  5.         <head>index</head> 
  6.         <body> 
  7.             <p>Welcome {0}!</p> 
  8.         </body> 
  9.     </html>'''.format(info)  

        现在我们就拥有了一个动态的页面,它能通过url中info/后面的字段作为变量,生成一个对应的页面。

       这个Web服务器也像那么回事了。

[python]  view plain  copy
  1. from flask import Flask  
  2. webapp =Flask(__name__)  
  3. @app.route('/')#路由  
  4. def index(): #视图函数  
  5.     return ''''' 
  6.     <html> 
  7.         <head>index</head> 
  8.         <body> 
  9.             <p>Welcome!</p> 
  10.         </body> 
  11.     </html>'''  
  12. @app.route('/info/<info>')#路由  
  13. def info(info): #视图函数  
  14.     return ''''' 
  15.     <html> 
  16.         <head>index</head> 
  17.         <body> 
  18.             <p>Welcome, {0}!</p> 
  19.         </body> 
  20.     </html>'''.format(info)  
  21. if __name__ ='__main__:  
  22.     webapp.run()  


四,现在我们为WEB添加更多的参数支持

[python]  view plain  copy
  1. form flask_script import Manager  
  2. webmanager =Manager(webapp)  
  3. #……………………  
  4. if __name__ = ‘__main__’:  
  5.        webmanager.run()  

现在我们可以在命令行使用如下的命令了(文件名为web.py):

       

[plain]  view plain  copy
  1. python3 web.py runserver –h 127.0.0.1 – p 8000  

制定ip 和端口启动服务器,如果你拥有外部IP,外网也可以访问了

五,这里简单介绍一下MVC,M-模型,V-视图,C-控制器。更多的自行百度……

简单说就是,用户发送一个请求,由控制器接受处理,返回一个(数据)模型,视图通过模型中的数据补充自己并渲染一个html页面返回给用户(这里是我自己的理解,只针对这一部分)

这里使用的渲染模版是jinja2,已整合进Flask。

那么可以对index方法进行如下修改:

[python]  view plain  copy
  1. from flask import render_template  
  2. @app.route('/info/<info>')  
  3. def info(info):#视图函数  
  4.     return render_template('info.html',info=info)  

然后在template/info.html中写入

[html]  view plain  copy
  1. <html>  
  2.         <head>index</head>  
  3.         <body>  
  4.             <p>Welcome {{ info }}!</p>  
  5.         </body>  
  6. </html>  

这样就能得到和之前一样的结果。这样的好处在于info.html页面可以被重复使用,更强大的是页面之间可以继承,重写,引入控制代码等等等等……

猜你喜欢

转载自blog.csdn.net/qq_41868948/article/details/80641881