我目前正在从一个补充服务的桌面应用程序实现一个到我的 Web 应用程序的 REST 接口。我们使用 Python 和 Flask 来实现 REST 服务器。
我们有一种情况,Java 客户端将请求 POST,而 python 服务器端将处理该帖子,直到它需要连接到 MySQL 数据库。
这是python/flask代码:
@app.route("/update_project/<project_data>", methods=['GET','POST'])
def updateWPProject(project_data):
"""project_data = user+++++pw+++++pj_jsondoc.
This will update an existing project data or insert a non-existant project data item."""
usrpw = project_data.split("+++++")
dblogin = wplogin(usr=usrpw[0], pw=usrpw[1])
if dblogin[0] == 'SUCCESS':
db_name = dblogin[1][0].strip()
db_user = dblogin[1][1].strip()
db_pw = dblogin[1][2].strip()
if flask.request.method == 'POST':
fname = flask.request.form['fName']
if fname:
pj = Project()
try:
pj = json.loads(fname)
except TypeError:
sys.stdout.write("JSON conversion error...%s" % sys.exc_info()[0])
except AttributeError:
sys.stdout.write("JSON conversion error...%s" % sys.exc_info()[0])
updateProject(db_name,db_user,db_pw,pj)
#return redirect(url_for('/'))
else:
return 'Login failure.'
pass
这工作得很好,直到它到达'updateProject(db_name,db_user,db_pw,pj)'行。然后它将转到该函数,并在 'cursor=conn.cursor()' 处返回 500,而无需完成该函数。
def updateProject(dbname, dbuser, dbpw, pj):
"""Updates or inserts a project record is not exists. PJ passed as an argument is a Project object."""
try:
conn = getConnection(dbuser, dbpw, dbname)
cursor = conn.cursor()
except:
sys.stdout.write("MySQL connection error...%s" % sys.exc_info()[0])
sql_stmt = """INSERT INTO projects( projNo, projName, worksteplabel, workstep1label, workstep2label, workstep3label, resultlabel, result1label, result2label, result3label, projectowner, dbname, dblogin, dbpw, role, preference1, preference2, preference3 )
VALUES (
'projNo', 'projName', 'wslabel', 'wslabel', 'wslabel', 'wslabel', 'rlabel', 'rlabel', 'rlabel', 'rlabel', 'pjowner', 'dbname', 'dblogin', 'dbpw', 'role', 'pref1', 'pref2', 'pref3'
) ON DUPLICATE
KEY UPDATE projName = 'projName',
worksteplabel = 'wslabel',
workstep1label = 'wslabel',
workstep2label = 'wslabel',
workstep3label = 'wslabel',
resultlabel = 'rlabel',
result1label = 'rlabel',
result2label = 'rlabel',
result3label = 'rlabel',
projectowner = 'pjowner',
dbname = 'dbname',
dblogin = 'dblogin',
dbpw = 'dbpw',
role = 'role',
preference1 = 'pref1',
preference2 = 'pref2',
preference3 = 'pref3' )
try:
cursor.execute(sql_stmt)
return 'SUCCESS'
except MySQLdb.Error:
sys.stdout.write("MySQLdb error...%s" % sys.exc_info()[0])
return 'FAILURE'
在 Java 客户端,我使用以下代码从客户端发送 POST 请求和数据。
public void DB_NewProjectREST(ProjectData proj, WPUser usr) {
// public static String excutePost(String targetURL, String urlParameters)
//URL url;
HttpURLConnection connection = null;
///First, all the GSON/JSon stuff up front
Gson gson = new Gson();
//convert java object to JSON format
String json = gson.toJson(proj);
//Then credentials and send string
String send_string = usr.getUserEmail()+"+++++"+usr.getUserHash();
try {
//Create connection
URL url = new URL("http://127.0.0.1:5000/update_project/"+send_string);
String urlParameters = "fName=" + URLEncoder.encode(json, "UTF-8");
connection = (HttpURLConnection)url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setRequestProperty("Content-Length", "" + Integer.toString(urlParameters.getBytes().length));
connection.setRequestProperty("Content-Language", "en-US");
connection.setUseCaches(false);
connection.setDoInput(true);
connection.setDoOutput(true);
//Send request
DataOutputStream wr = new DataOutputStream (connection.getOutputStream ());
wr.writeBytes (urlParameters);
wr.flush ();
wr.close ();
//Get Response
InputStream is = connection.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
String line;
StringBuffer response = new StringBuffer();
while((line = rd.readLine()) != null) {
response.append(line);
response.append('\r');
}
rd.close();
} catch (Exception e) {
e.printStackTrace();
//return null;
}finally {
if(connection != null) {
connection.disconnect();
}
}
}
似乎我必须将某种响应(对于输入流)发送回客户端,这就是我的 python 代码突然返回的地方。(?)数据从 java 客户端获取到 python/flask 代码,那么有什么方法可以快速返回“OK”并继续处理数据库更新。或者,python updateProject 函数中的游标连接调用是否以某种方式干扰了 http 连接?
任何帮助表示赞赏。