Flask 实践1

2018-03-09  本文已影响0人  可爱喵星人

1.一个简单的应用

#app.py
from flask import Flask

app = Flask('__name__')

@app.route('/')
def home():
    return 'hello world'

if __name__ == '__main__':
    app.run()

命令行执行 python app.py
浏览器输入:http://localhost:5000/

simpleapp.png

2.跳转到静态html

#app.py
from flask import Flask

app = Flask('__name__', static_url_path='')


@app.route('/')
def home():    
    return app.send_static_file('view/index.html')


@app.route('/sigin', methods=['GET'])
def singin():
    return app.send_static_file('view/singin.html')


@app.route('/sigin', methods=['POST'])
def main():
    return app.send_static_file('view/main.html')


if __name__ == '__main__':
    app.run()

文件结构:


图片.png
<h1>Home</h1>
<html>
    <form action="/sigin" method="post">
        <p><input name="username"></p>
        <p><input name="password"></p>
        <p><button type="submit">Sign In</button></p>
    </form>
</html>
<h3>hello world</h3>

3.模板

模板内容大致如下:

<html>
<head>
  <title>Error Page</title>
</head>
<body>
  <p>Username ( {{ username }} )is error or password ({{pwd}}) is error</p>
</body>
</html>
from flask import Flask, request, render_template

app = Flask('__name__', static_url_path='')


@app.route('/')
def home():
   return app.send_static_file('view/index.html')


@app.route('/sigin', methods=['GET'])
def singin():
   return app.send_static_file('view/singin.html')


@app.route('/sigin', methods=['POST'])
def main():
   name = request.form['username']
   password = request.form['password']
   if (name == 'user' and password == 'pwd'):
       return app.send_static_file('view/main.html')
   else:
       return render_template('error.html', username=name, pwd=password)


if __name__ == '__main__':
   app.run()
def render_template(template_name_or_list, **context):
    """Renders a template from the template folder with the given
    context.

    :param template_name_or_list: the name of the template to be
                                  rendered, or an iterable with template names
                                  the first one existing will be rendered
    :param context: the variables that should be available in the
                    context of the template.
    """
    ctx = _app_ctx_stack.top
    ctx.app.update_template_context(context)
    return _render(ctx.app.jinja_env.get_or_select_template(template_name_or_list),
                   context, ctx.app)
def _render(template, context, app):
    """Renders the template and fires the signal"""
    before_render_template.send(app, template=template, context=context)
    rv = template.render(context)
    template_rendered.send(app, template=template, context=context)
    return rv

参考

flask官网: http://flask.pocoo.org/docs/0.12/quickstart/#a-minimal-application
廖雪峰Python:https://www.liaoxuefeng.com/wiki/0014316089557264a6b348958f449949df42a6d3a2e542c000/001432012745805707cb9f00a484d968c72dbb7cfc90b91000

上一篇 下一篇

猜你喜欢

热点阅读