On Windows 10, I use cmder as the console emulator. See dsnote 'Cmder和ConEmu笔记' for details about setting up cmder.
The package flask-mysql
used by the server is incompatible with Python 3.6,
so we use Python 2.7 instead.
Anaconda instead of Python Windows installer is used to build
Python environment, because Anaconda can manage Python environment easily
with conda
utility.
First install Anaconda, add c:\Users\lee_c\Anaconda3\Scripts
to %PATH%
to enable command conda
in console.
Then create a new Python 2.7 environment with
conda create -n flask-mysql-server python=2.7
.
Activate it with activate flask-mysql-server
.
Install packages in this environment: pip install flask-mysql flask-cors
.
Create server script:
# -*- coding: utf-8 -*-
from flask import Flask, render_template, json, request, flash, redirect, url_for
from flaskext.mysql import MySQL
from flask_cors import CORS, cross_origin
mysql = MySQL()
app = Flask(__name__)
app.secret_key = 'fuzhuo dasha'
CORS(app)
app.config['MYSQL_DATABASE_USER'] = 'root'
app.config['MYSQL_DATABASE_PASSWORD'] = 'zhangjingg'
app.config['MYSQL_DATABASE_DB'] = 'test'
app.config['MYSQL_DATABASE_HOST'] = 'localhost'
mysql.init_app(app)
conn = mysql.connect()
cursor = conn.cursor()
@app.route('/')
def index():
return "Hello, World!"
@app.route('/groups/add', methods=['POST'])
def add_group():
data = request.get_json()
cursor.execute('insert into groups (user, groupName) values (%s, %s)', [data['user'], data['grpname']])
conn.commit()
return 'insert success'
@app.route('/groups/del/<gid>', methods=['POST'])
def del_group(gid):
data = request.get_json()
cursor.execute('delete from groups where GrpID = %s', gid)
conn.commit()
return 'delete success'
@app.route('/groups/edit/<gid>', methods=['POST'])
def edit_group(gid):
data = request.get_json()
sqlstr = "update groups set groupName = '%s' where GrpID = %s" % (data['grpname'], gid)
print('Execute SQL: ' + sqlstr)
cursor.execute(sqlstr)
conn.commit()
return 'edit success'
if __name__ == '__main__':
app.run(port=5000, debug=True)
And run: python app.py
.
Test it in a new cygwin window:
curl -i -X POST -H "Content-Type: application/json" http://127.0.0.1:5000/groups/add -d '{"user": 2, "grpname": "我的新组"}'
.
Note: You can't run above command in cygwin,
because command activate
and source
doesn't work in cygwin.