Skip to content

Instantly share code, notes, and snippets.

@peace098beat
Created March 2, 2016 05:43
Show Gist options
  • Save peace098beat/bb037b5230e5ad612692 to your computer and use it in GitHub Desktop.
Save peace098beat/bb037b5230e5ad612692 to your computer and use it in GitHub Desktop.
[Ajax + Python CGI] python cgi でjsonを扱う
#!C:\Anaconda2_32bit\python.exe
# -*- coding: utf-8 -*-
import cgitb
cgitb.enable()
import cgi
import os
import sys
import json
##########################################
# DBへアクセス
##########################################
import sqlite3
conn = sqlite3.connect('./db_example')
c = conn.cursor()
# Create table
c.execute('SELECT * FROM tbl_gpx')
data = []
for row in c:
data.append(row)
pass
json_data = json.dumps(data)
# Save (commit) the changes
conn.commit()
# We can also close the cursor if we are done with it
c.close()
##########################################
# レスポンス
##########################################
print "Content-Type: text/javascript\n\n"
print
print json_data
#!C:\Anaconda2_32bit\python.exe
# -*- coding: utf-8 -*-
"""
Ajax経由でデータを取得し,データベースへ保存
"""
import cgitb
cgitb.enable()
import cgi
import os
import sys
import json
import os
##########################################
# レスポンス
##########################################
# (おまじない)
# print "Content-type: text/javascript; charset=utf-8"
# print
print ('Content-type: text/html; charset=UTF-8')
print ("\r\n\r\n")
##########################################
# POSTからデータ取得
##########################################
#POSTデータ判定
if ( os.environ['REQUEST_METHOD'] != "POST" ):
print (u"METHOD不正")
# # POSTのオブジェクトを取得
form = cgi.FieldStorage()
for key in form.keys():
variable = str(key)
value = str(form.getvalue(variable))
# print "<p>"+ variable +", "+ value +"</p>\n"
xml_data = json.loads(value)
print xml_data["trk"]["trkseg"]["trkpt"][0]
print xml_data["trk"]["trkseg"]["trkpt"][0]["lat"]
print xml_data["trk"]["trkseg"]["trkpt"][0]["time"]
print xml_data["trk"]["trkseg"]["trkpt"][0]["lon"]
print xml_data["trk"]["trkseg"]["trkpt"][0]["ele"]
datas = xml_data["trk"]["trkseg"]["trkpt"]
##########################################
# DBへアクセス
##########################################
import sqlite3
conn = sqlite3.connect('./db_gpx')
c = conn.cursor()
# テーブルを削除するなら
c.execute('''DROP TABLE IF EXISTS tbl_gpx ''')
# テストなので,DBを新しく作る
c.execute('''CREATE TABLE IF NOT EXISTS tbl_gpx (
id integer primary key,
lat,
time,
lon,
ele
)''')
for data in datas:
lat = data["lat"]
time = data["time"]
lon = data["lon"]
ele = data["ele"]
# Ajaxで受けたデータをDBに保存
c.execute("""INSERT INTO tbl_gpx (lat,time,lon,ele) VALUES (?,?,?,?)""", (lat,time,lon,ele))
# Save (commit) the changes
conn.commit()
# We can also close the cursor if we are done with it
c.close()
<html lang="en">
<head>
<meta charset="utf-8">
<title>Ajaxアクセステンプレート</title>
</head>
<style type="text/css">
#drop_zone {
border: 2px dashed #bbb;
-moz-border-radius: 5px;
-webkit-border-radius: 5px;
border-radius: 5px;
padding: 25px;
text-align: center;
font: 20pt bold 'Vollkorn';
color: #bbb;
}
.thumb {
height: 75px;
border: 1px solid #000;
margin: 10px 5px 0 0;
}
</style>
<body>
<h1>Hello, world!</h1>
<button onclick="server_load_Json()">load</button>
<button onclick="server_save_Json()">save</button>
<h3><a hfre="http://www.html5rocks.com/ja/tutorials/file/dndfiles/">JavaScriptでFileAPIを使用してファイルを読み込む</a></h3>
<div id="drop_zone">Drop files here</div>
<!-- <input type="file" id="files" name="files[]" multiple /> -->
<div id="file-name"></div>
<div id="result"></div>
<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="jquery.xml2json.js" type="text/javascript" language="javascript"></script>
</body>
<script>
global_JSON = [];
/*
* JavaScriptでFileAPIを使用してファイルを読み込
* http://www.html5rocks.com/ja/tutorials/file/dndfiles/
* http://tmlife.net/programming/javascript/html5-file-api-file-read.html
* https://app.codegrid.net/entry/file-api-filereader-api
*/
var reader = new FileReader();
function handleFileSelect(evt) {
// (おまじない) これがないとtextファイルをそのままブラウザでひらいちゃう
evt.stopPropagation();
evt.preventDefault();
// ファイルリストを取得
var files = evt.dataTransfer.files; // FileList object
console.log(files);
for (var i = 0; i < files.length; i++) {
readfile(files[i]);
}
// ファイルの読み込み関数オープン
// readfile(files[0]);
}
function readfile(file){
console.log('readfile(file) > reader.onload() > run')
var reader = new FileReader();
reader.onload = (function(theFile) {
return function(e) {
console.log(e.target.result);
var json = $.xml2json(e.target.result);
console.log(json);
console.log(json.trk.name);
console.log(json.trk.trkseg.trkpt);
global_JSON = json;
$("#file-name").append("<p>" + escape(theFile.name) + "</p>")
// $("#result").text(e.target.result)
};
})(file);
var encode_type = 'shift-jis'
reader.readAsText(file, encode_type)
}
function handleDragOver(evt) {
evt.stopPropagation();
evt.preventDefault();
evt.dataTransfer.dropEffect = 'copy'; // Explicitly show this is a copy.
}
// Setup the dnd listeners.
var dropZone = document.getElementById('drop_zone');
dropZone.addEventListener('dragover', handleDragOver, false);
dropZone.addEventListener('drop', handleFileSelect, false);
</script>
<script type="text/javascript">
/* *****************************************
*
*
*
/*******************************************/
// 返却されたデータを格納するグローバル変数
global_result = []
$(function(){
console.log("SCRIPT LOAD ..")
// Check for the various File API support.
if (window.File && window.FileReader && window.FileList && window.Blob) {
// Great success! All the File APIs are supported.
} else {
alert('The File APIs are not fully supported in this browser.');
}
});
function server_load_Json() {
/*
* サーバー上のCGIスクリプトを実行し
* データを取得
*
*/
console.log("server_load_Json ..")
$.ajax({
url: "/cgi-bin/ajax-demo/api/api_json_load.py",
type: "POST",
//必要ないがサーバ側との整合のために明示しておいた方がよい。
// contentType: "Content-Type: application/json; charset=UTF-8",
// 必要ないがサーバ側との整合のために明示しておいた方がよい。
// dataType: 'json' //受信形式
// data:send_data
}).success(function(data, status, xhr) {
console.log("/* 通信成功 server_load_Json */");
console.log("success");
console.log("data =" + data);
console.log("data.length =" + data.length);
console.log("status =" + status);
console.log("xhr =" + xhr);
console.log("> load data (JSON) :" + data);
// 得られたJSONデータをパース
global_result = JSON.parse(data);
console.log("> パース後のデータ data :" + global_result);
// 取得した結果をjQueryを使ってHTML内部に書き出し
$('#result').text(global_result);
}).error(function(xhr, status, error) {
// 通信失敗時の処理
console.log("/* 通信失敗 */");
}).complete(function(xhr, status) {
// 通信完了時の処理
console.log("/* 通信終了 */");
});
}
function server_save_Json() {
/*
* サーバー上のCGIスクリプトを実行し
* データを取得
*
*/
// 現在の時刻を取得
// var date_obj = new Date();
// 時刻を文字列で取得
// date = date_obj.toLocaleString()
// POSTで送るように,生計
// send_data = {date:date}
// send_data = global_JSON;
// name = global_JSON.trk.name;
// trkpt = global_JSON.trk.trkseg.trkpt;
// send_data = {json:global_JSON};
// global_JSON = {
// "no1": [1,2,3],
// "no2": [4,5,6]
// }
global_JSON = JSON.stringify(global_JSON);
send_data = {data:global_JSON}
console.log(send_data);
console.log("server_save_Json ..")
$.ajax({
url: "/cgi-bin/ajax-demo/api/api_json_save.py",
type: "POST",
//必要ないがサーバ側との整合のために明示しておいた方がよい。
// contentType: "Content-Type: application/json; charset=UTF-8",
// 必要ないがサーバ側との整合のために明示しておいた方がよい。
// dataType: 'json', //受信形式
data:send_data
}).success(function(data, status, xhr) {
console.log("/* 通信成功 server_save_Json*/");
console.log("success");
console.log("data =" + data);
console.log("data.length =" + data.length);
console.log("status =" + status);
console.log("xhr =" + xhr);
$("#result").append(data);
}).error(function(xhr, status, error) {
// 通信失敗時の処理
console.log("/* 通信失敗 */");
$("#result").append("<p>"+xhr);
$("#result").append("<p>"+status);
$("#result").append("<p>"+error);
}).complete(function(xhr, status) {
// 通信完了時の処理
console.log("/* 通信終了 */");
});
}
</script>
</html>
/*
### jQuery XML to JSON Plugin v1.3 - 2013-02-18 ###
* http://www.fyneworks.com/ - [email protected]
* Licensed under http://en.wikipedia.org/wiki/MIT_License
###
Website: http://www.fyneworks.com/jquery/xml-to-json/
*//*
# INSPIRED BY: http://www.terracoder.com/
AND: http://www.thomasfrank.se/xml_to_json.html
AND: http://www.kawa.net/works/js/xml/objtree-e.html
*//*
This simple script converts XML (document of code) into a JSON object. It is the combination of 2
'xml to json' great parsers (see below) which allows for both 'simple' and 'extended' parsing modes.
*/
// Avoid collisions
;if(window.jQuery) (function($){
// Add function to jQuery namespace
$.extend({
// converts xml documents and xml text to json object
xml2json: function(xml, extended) {
if(!xml) return {}; // quick fail
//### PARSER LIBRARY
// Core function
function parseXML(node, simple){
if(!node) return null;
var txt = '', obj = null, att = null;
var nt = node.nodeType, nn = jsVar(node.localName || node.nodeName);
var nv = node.text || node.nodeValue || '';
/*DBG*/ //if(window.console) console.log(['x2j',nn,nt,nv.length+' bytes']);
if(node.childNodes){
if(node.childNodes.length>0){
/*DBG*/ //if(window.console) console.log(['x2j',nn,'CHILDREN',node.childNodes]);
$.each(node.childNodes, function(n,cn){
var cnt = cn.nodeType, cnn = jsVar(cn.localName || cn.nodeName);
var cnv = cn.text || cn.nodeValue || '';
/*DBG*/ //if(window.console) console.log(['x2j',nn,'node>a',cnn,cnt,cnv]);
if(cnt == 8){
/*DBG*/ //if(window.console) console.log(['x2j',nn,'node>b',cnn,'COMMENT (ignore)']);
return; // ignore comment node
}
else if(cnt == 3 || cnt == 4 || !cnn){
// ignore white-space in between tags
if(cnv.match(/^\s+$/)){
/*DBG*/ //if(window.console) console.log(['x2j',nn,'node>c',cnn,'WHITE-SPACE (ignore)']);
return;
};
/*DBG*/ //if(window.console) console.log(['x2j',nn,'node>d',cnn,'TEXT']);
txt += cnv.replace(/^\s+/,'').replace(/\s+$/,'');
// make sure we ditch trailing spaces from markup
}
else{
/*DBG*/ //if(window.console) console.log(['x2j',nn,'node>e',cnn,'OBJECT']);
obj = obj || {};
if(obj[cnn]){
/*DBG*/ //if(window.console) console.log(['x2j',nn,'node>f',cnn,'ARRAY']);
// http://forum.jquery.com/topic/jquery-jquery-xml2json-problems-when-siblings-of-the-same-tagname-only-have-a-textnode-as-a-child
if(!obj[cnn].length) obj[cnn] = myArr(obj[cnn]);
obj[cnn] = myArr(obj[cnn]);
obj[cnn][ obj[cnn].length ] = parseXML(cn, true/* simple */);
obj[cnn].length = obj[cnn].length;
}
else{
/*DBG*/ //if(window.console) console.log(['x2j',nn,'node>g',cnn,'dig deeper...']);
obj[cnn] = parseXML(cn);
};
};
});
};//node.childNodes.length>0
};//node.childNodes
if(node.attributes){
if(node.attributes.length>0){
/*DBG*/ //if(window.console) console.log(['x2j',nn,'ATTRIBUTES',node.attributes])
att = {}; obj = obj || {};
$.each(node.attributes, function(a,at){
var atn = jsVar(at.name), atv = at.value;
att[atn] = atv;
if(obj[atn]){
/*DBG*/ //if(window.console) console.log(['x2j',nn,'attr>',atn,'ARRAY']);
// http://forum.jquery.com/topic/jquery-jquery-xml2json-problems-when-siblings-of-the-same-tagname-only-have-a-textnode-as-a-child
//if(!obj[atn].length) obj[atn] = myArr(obj[atn]);//[ obj[ atn ] ];
obj[cnn] = myArr(obj[cnn]);
obj[atn][ obj[atn].length ] = atv;
obj[atn].length = obj[atn].length;
}
else{
/*DBG*/ //if(window.console) console.log(['x2j',nn,'attr>',atn,'TEXT']);
obj[atn] = atv;
};
});
//obj['attributes'] = att;
};//node.attributes.length>0
};//node.attributes
if(obj){
obj = $.extend( (txt!='' ? new String(txt) : {}),/* {text:txt},*/ obj || {}/*, att || {}*/);
//txt = (obj.text) ? (typeof(obj.text)=='object' ? obj.text : [obj.text || '']).concat([txt]) : txt;
txt = (obj.text) ? ([obj.text || '']).concat([txt]) : txt;
if(txt) obj.text = txt;
txt = '';
};
var out = obj || txt;
//console.log([extended, simple, out]);
if(extended){
if(txt) out = {};//new String(out);
txt = out.text || txt || '';
if(txt) out.text = txt;
if(!simple) out = myArr(out);
};
return out;
};// parseXML
// Core Function End
// Utility functions
var jsVar = function(s){ return String(s || '').replace(/-/g,"_"); };
// NEW isNum function: 01/09/2010
// Thanks to Emile Grau, GigaTecnologies S.L., www.gigatransfer.com, www.mygigamail.com
function isNum(s){
// based on utility function isNum from xml2json plugin (http://www.fyneworks.com/ - [email protected])
// few bugs corrected from original function :
// - syntax error : regexp.test(string) instead of string.test(reg)
// - regexp modified to accept comma as decimal mark (latin syntax : 25,24 )
// - regexp modified to reject if no number before decimal mark : ".7" is not accepted
// - string is "trimmed", allowing to accept space at the beginning and end of string
var regexp=/^((-)?([0-9]+)(([\.\,]{0,1})([0-9]+))?$)/
return (typeof s == "number") || regexp.test(String((s && typeof s == "string") ? jQuery.trim(s) : ''));
};
// OLD isNum function: (for reference only)
//var isNum = function(s){ return (typeof s == "number") || String((s && typeof s == "string") ? s : '').test(/^((-)?([0-9]*)((\.{0,1})([0-9]+))?$)/); };
var myArr = function(o){
// http://forum.jquery.com/topic/jquery-jquery-xml2json-problems-when-siblings-of-the-same-tagname-only-have-a-textnode-as-a-child
//if(!o.length) o = [ o ]; o.length=o.length;
if(!$.isArray(o)) o = [ o ]; o.length=o.length;
// here is where you can attach additional functionality, such as searching and sorting...
return o;
};
// Utility functions End
//### PARSER LIBRARY END
// Convert plain text to xml
if(typeof xml=='string') xml = $.text2xml(xml);
// Quick fail if not xml (or if this is a node)
if(!xml.nodeType) return;
if(xml.nodeType == 3 || xml.nodeType == 4) return xml.nodeValue;
// Find xml root node
var root = (xml.nodeType == 9) ? xml.documentElement : xml;
// Convert xml to json
var out = parseXML(root, true /* simple */);
// Clean-up memory
xml = null; root = null;
// Send output
return out;
},
// Convert text to XML DOM
text2xml: function(str) {
// NOTE: I'd like to use jQuery for this, but jQuery makes all tags uppercase
//return $(xml)[0];
/* prior to jquery 1.9 */
/*
var out;
try{
var xml = ((!$.support.opacity && !$.support.style))?new ActiveXObject("Microsoft.XMLDOM"):new DOMParser();
xml.async = false;
}catch(e){ throw new Error("XML Parser could not be instantiated") };
try{
if((!$.support.opacity && !$.support.style)) out = (xml.loadXML(str))?xml:false;
else out = xml.parseFromString(str, "text/xml");
}catch(e){ throw new Error("Error parsing XML string") };
return out;
*/
/* jquery 1.9+ */
return $.parseXML(str);
}
}); // extend $
})(jQuery);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment