現在、サービスを補完するデスクトップ アプリケーションから Web アプリケーションへの REST インターフェイスを実装しています。REST サーバーの実装には Python と Flask を使用しています。
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 接続に干渉していませんか?
どんな助けでも感謝します。