和django相比,Flask真是轻。也没那么多复杂。

一、简单模版
下面是__init__.py文件:

import os
from flask import Flask
from flask_cors import CORS # 导入模块
from markupsafe import escape
from flask import request
import json
from flask import jsonify
from flask_login import login_manager, UserMixin
import pandas as pd
#from flask_cors import cross_origindef create_app(test_config=None):# create and configure the appapp = Flask(__name__, instance_relative_config=True)CORS(app, supports_credentials=True)  # 设置跨域app.config.from_mapping(SECRET_KEY='dev',DATABASE=os.path.join(app.instance_path, 'flaskr.sqlite'),)if test_config is None:# load the instance config, if it exists, when not testingapp.config.from_pyfile('config.py', silent=True)else:# load the test config if passed inapp.config.from_mapping(test_config)# ensure the instance folder existstry:os.makedirs(app.instance_path)except OSError:pass## 无变量@app.route('/', strict_slashes=False)def index():username = request.cookies.get('username')## 单变量或无变量,只能GET@app.route('/hello/<username>',methods=['GET'], strict_slashes=False)def hello(username):return f' Hello, {escape(username)}'## 登陆@app.route('/login', methods=['POST'],strict_slashes=False)def login(): ## 以下只是示例,返回tokenif valid_login(request.form['username'],request.form['password']):token = request.form['username']+ "--abcdefghighk1234567--" + request.form['password']return tokenelse:error = 'Invalid username/password'return "------error------"## 多变量,可以接受POST和GET,均可## 取特定标的、日期范围的数据@app.route('/data/<string:code>/<string:startdate>/<string:closedate>/',methods=['POST',"GET"], strict_slashes=False)def get_data(code,startdate,closedate):## 需要比照用户名和tokenif request.method == "POST": csv_path = r"C:\Users\admin\Desktop\test.csv"df = pd.read_csv(csv_path)dict = df.to_dict("dict")json = jsonify(dict)  #df.to_json(orient = "table") #'table',valuesreturn jsonelse:data = {"code": code,"startdate": startdate,"closedate": closedate,"data" :{"code":code,"close":[1.0,2.0,3.0,4.0]}}json_str = jsonify(data) ## 用jsonify好,不推荐json.dumps(data) return json_str## 方法结束return app# if __name__ == '__main__':
#     app = create_app()
#     app.run(host="0.0.0.0", port=5000, debug=True)def valid_login(username,password): # only test!user_names = ["test"]if username in user_names  and password != "":return Trueelse:return Falsedef log_the_user_in(username):pass

二、WINDOW环境

1、安装和环境
具体可以参考:

https://dormousehole.readthedocs.io/en/latest/

很详细,一步步来。
2、几点说明

(1)所有的操作在venv中进行,包括下载包和程序运行。

python3 -m venv venv 创建虚拟环境

或者,如果不行,试试下面这个:

py -3 -m venv venv

(2)设置跨域很重要

 CORS(app, supports_credentials=True)  # 设置跨域,很重要!!

(3)init.py是入口或改成app.py

(4) 关于render_templates与templates文件夹位置
如果templates文件夹位置不对,render_templates函数一直会找不到相应的html文件,哪怕你写的是绝对路径。
在上面,web_api是FLASK_APP; templates文件夹应与__init__.py在同一级目录下。这样就没有问题了。

(5)运行前的操作:【操作的路径很重要!!!!】

假定需要创建一个名为dingtou的目录(其中, web_api为具体项目名称,需要根据自己情况配置,就是__init__.py的文件夹):

在dingtou 目录 下(注意:目录不对,会找不到,这个很重要!!!!!!),分别:

python3 -m venv venv # 或 py -3 -m venv venv
venv\Scripts\activate

在 venv下:

set FLASK_APP=web_api
set FLASK_ENV=development
flask run

注意:cmd和powershell的操作还不一样。

相当于开放外网而不仅是本地访问的权限,

>flask run --host=0.0.0.0

外网是否能访问还要设置好防火墙:

Usage: flask run [OPTIONS]Run a local development server.This server is for development purposes only. It does not provide thestability, security, or performance of production WSGI servers.The reloader and debugger are enabled by default if FLASK_ENV=development orFLASK_DEBUG=1.Options:-h, --host TEXT                 The interface to bind to.-p, --port INTEGER              The port to bind to.--cert PATH                     Specify a certificate file to use HTTPS.--key FILE                      The key file to use when specifying acertificate.--reload / --no-reload          Enable or disable the reloader. By defaultthe reloader is active if debug is enabled.--debugger / --no-debugger      Enable or disable the debugger. By defaultthe debugger is active if debug is enabled.--eager-loading / --lazy-loadingEnable or disable eager loading. By defaulteager loading is enabled if the reloader isdisabled.--with-threads / --without-threadsEnable or disable multithreading.--extra-files PATH              Extra files that trigger a reload on change.Multiple paths are separated by ';'.--help                          Show this message and exit.

三、ubuntu开发环境
其中,flaskyi替换成具体项目的名称:

在前入venv前(项目路径下):

python3 -m venv venv
source venv/bin/activate

在前入venv后:

export FLASK_APP=flasky
flask run

四、ubuntu生产环境[碰到问题]

待续…

flask run --host=0.0.0.0

如果在venv环境中找不到pip,请用:

python -m pip install --upgrade pip

关闭虚拟环境

 deactivate

如何找不到flask(No module named flask 错误解决),可以:

virtualenv flask

部署Flask环境

在本地生成requirements.txt文件
pip freeze > requirements.txt
然后在服务器虚拟环境中安装requirements.txt依赖
pip install -r requirements.txtsudo apt-get install uwsgi-plugin-python

网页访问:

$ sudo apt-get install w3m
$ w3m www.baidu.com

注意w3m命令, 按q 退出(需确认) 。

Python: Flask后端与webapi相关推荐

  1. 微信小程序+Python Flask后端实战开发案例

    微信小程序安装 因为作者操作系统是Ubuntu16.04 所以在安装小程序开发平台时也踩了不少坑 首先 下载项目和初始化 git clone https://github.com/cytle/wech ...

  2. python flask高级编程之restful_('Python Flask高级编程之RESTFul API前后端分离精讲',),全套视频教程学习资料通过百度云网盘下载...

    资源详情 r n t某课网好评度100%的Python Flask高级编程之RESTFul API前后端分离精讲 r n t t t第1章 随便聊聊 r n t t t聊聊Flask与Django,聊 ...

  3. html文件怎么用Python做后端,利用python实现后端写网页(flask框架).pdf

    利利用用python实实现现后后端端写写网网页页 ((flask框框架架)) 如何用python做后端写网页-flask框架 什么是Flask安装flask模块Hello World更深一步:数据绑 ...

  4. python flask webapi_在将Python Flask webapi部署到azurep时遇到依赖性问题

    我试图将python flask webapi部署到azureportal,但是在安装依赖关系时遇到了问题,如下图所示. 我已经在我的azure web应用程序中添加了扩展-Python3.5.4 x ...

  5. 【python学习笔记】关于python Flask前后端分离跨域问题

    关于python Flask前后端分离跨域问题 前后端分离过程中,前后端对接测试难免遇到跨域问题.因为是个新司机,所以在我经过一天的测试,才找到解决办法=-= 第一种方法 from functools ...

  6. Mysql+Echarts+Python+Flask实现前后端交互及数据可视化

    前言 社区版Pycharm实现python+flask+echarts+Mysql实现简单的前后端交互. 新手入门,记录经验,欢迎交流. 一.首先检测Flask框架是否成功? 首先,在你的项目下中安装 ...

  7. 如何用python做后端写网页-flask框架

    如何用python做后端写网页-flask框架 什么是Flask 安装flask模块 Hello World 更深一步:数据绑定 后端传入数据 从前端获取数据 数据库连接 screen 创建后台 查看 ...

  8. Python前后端交互( Flask Ajax )

    本文是自己学习Python前后端交互记录使用,之前没有学习过Python任何框架,前端也是简单学了一下,如哪里有问题,还望大家批评改正. 1. 前端 1.1 HTML布局 这个就不用说啥了,登录长啥样 ...

  9. Vue前后端页面下载功能实现演示,Python+flask提供后台下载服务

    Vue前后端页面下载功能实现 效果图 后台下载服务实现 前台简单实现 [ 文章推荐 ] Python 地图篇 - 使用 pyecharts 绘制世界地图.中国地图.省级地图.市级地图实例详解 效果图 ...

  10. python flask restful入门_Python Flask高级编程之RESTFul API前后端分离精讲

    第1章 随便聊聊 聊聊Flask与Django,聊聊代码的创造性1-1 Flask VS Django 1-2 课程更新维护说明 第2章 起步与红图 本章我们初始化项目,探讨与研究Flask的默认层级 ...

最新文章

  1. The C10K problem原文翻译
  2. 人脑启发AI设计:让神经网络统一翻译语音和文本
  3. 【一周入门MySQL—2】单表查询
  4. python 各层级目录下的import方法
  5. 产品经理 - 学习书籍
  6. ggbiplot设置分组_R语言安装ggbiplot
  7. 在SQL Server 2008中调用.net,dll
  8. 【源码】net_device结构
  9. 真实项目中 ThreadLocal 的妙用
  10. .Net 1.1下WEB引用Win控件的两个Bug
  11. ES学习笔记之-ClusterState的学习
  12. 最短路径之弗洛伊德算法
  13. 苹果Mac临时文件存储助手工具:Yoink
  14. [POJ3177]Redundant Paths
  15. 【查找资料】冰点文档下载免费下载百度、豆丁、丁香、畅享、MBALib、道客巴巴、Book118等文库文档
  16. LeetCode 69. x 的平方根
  17. 斐讯K2 E1 刷老毛子Padavan中继图文教程(与主路由同网段)
  18. android+特殊符号过滤,android 特殊符号过滤
  19. rstudio 连接mysql_Rstudio ODBC 连接MySQL
  20. java截图+中文图片识别

热门文章

  1. Linux中线程使用详解
  2. androidManifest
  3. JS魔法堂:LINK元素深入详解
  4. 十五天精通WCF——第四天 你一定要明白的通信单元Message
  5. 秋招已过,各大厂的面试题分享一波 附C++实现
  6. 【Gulp自动化构建工具】
  7. Nodejs Web模块( readFile 根据请求跳转到响应html )
  8. ZendFramework-2.4 源代码 - 整体架构(类图)
  9. Thrift框架简介
  10. Content-type 对照表