Skip to content

Commit

Permalink
完全使用sqlite 返回数据
Browse files Browse the repository at this point in the history
android 也增加了提交数据环节,数据可以提交入sqlite
  • Loading branch information
Fox.Lee committed Nov 27, 2012
1 parent d18b9a1 commit 496274a
Show file tree
Hide file tree
Showing 29 changed files with 593 additions and 2 deletions.
19 changes: 18 additions & 1 deletion 24-P321-from_pickle_toSQLite/athletemodel.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
#import pickle
########使用sqlite 创建新的模型
import sqlite3

from athletelist import AthleteList
Expand All @@ -22,15 +22,32 @@ def get_athlete_from_id(athlete_id):
(name, dob) = results.fetchone()
results = cursor.execute("""SELECT value FROM timing_data WHERE athlete_id=?""",
(athlete_id,))
#从查询结果中得到数据,转化为一个字典
response = { 'Name': name,
'DOB': dob,
'data': data,
'top3': data[0:3]}
connection.close()
return(response)

def get_namesID_from_store():
connection = sqlite3.connect(db_name)
cursor = connection.cursor()
results = cursor.execute("""SELECT name,id FROM athletes""")
response = results.fetchall()
connection.close()
return(response)

"""测试代码
data = get_namesID_from_store()
print (data)
print (data[0][0])
"""

##########sqlite模型

#####旧的模型使用的是pickle
import pickle
def get_coach_data(filename): #从文件中获取数据

try:
Expand Down
Binary file modified 24-P321-from_pickle_toSQLite/athletes.pickle
Binary file not shown.
Binary file modified 24-P321-from_pickle_toSQLite/coachdata.sqlite
Binary file not shown.
2 changes: 1 addition & 1 deletion 24-P321-from_pickle_toSQLite/from_pickle_toSQLite.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@

#插入time_data 表
cursor.execute("SELECT id FROM athletes WHERE name=? and dob=?",(name,dob))
the_current_id = cursor.fetchone()[0]
the_current_id = cursor.fetchone()[0]# fetchone 返回一个列表
for each_time in athletes[each_ath].clean_data:
cursor.execute("INSERT INTO timing_data(athlete_id,value) VALUES(?,?)",(the_current_id,each_time))

Expand Down
80 changes: 80 additions & 0 deletions 24-P337-sqlite-neweb/ad-coachapp.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
import android
import json
import time
import sys

from urllib.parse import urlencode
from urllib.request import urlopen

#app 的所有消息
hello_msg = "Welcome to Coach Kelly's Timing App"
list_title = 'Here is your list of athletes'
quit_msg = "Quitting Coach Kelly's App."
web_server = 'http://192.168.1.180:8082'
get_name_cgi = '/cgi-bin/generate_name.py'

get_data_cgi = '/cgi-bin/generate_data.py'


#send to server 取一个web地址(url) 和一些可选数据(post_data)
#它向web 服务器发送一份web请求(urlopen)
#web响应返回给调用者(return)
def send_to_server(url, post_data=None):
if post_data:
page = urlopen(url,urlencode(post_data).encode('utf-8'))
else:
page = urlopen(url)
return(page.read().decode('utf-8'))

app = android.Android()

def status_update(msg, how_long = 2 ):
app.makeToast(msg)
time.sleep(how_long)

status_update(hello_msg)


#athlete_names = sorted (json.loads(send_to_server(web_server + get_name_cgi)))
athletes = sorted (json.loads(send_to_server(web_server + get_name_cgi)))
athlete_names = [ath[0] for ath in athletes]

app.dialogCreateAlert(list_title)
app.dialogSetSingleChoiceItems(athlete_names)
app.dialogSetPositiveButtonText('Select')
app.dialogSetNegativeButtonText('Quit')
app.dialogShow()
resp = app.dialogGetResponse().result


if resp['which'] in ('positive'):
selected_athlete = app.dialogGetSelectedItems().result[0]
#which_athlete = athlete_names[selected_athlete]
which_athlete = athletes[selected_athlete][1]#确定选手关联的id
#print("####"+str(which_athlete)+"###", file=sys.stderr)
athlete = json.loads(send_to_server(web_server + get_data_cgi,{'which_athlete': which_athlete}))
athlete_title = athlete['Name'] + '(' + athlete['DOB'] + '), top 3 times:'
app.dialogCreateAlert(athlete_title)
#app.dialogSetItems(athlete['Top3'])
app.dialogSetItems(athlete['top3'])
app.dialogSetPositiveButtonText('OK')

app.dialogSetNegativeButtonText('Add Time')

app.dialogShow()
resp = app.dialogGetResponse().result

if resp['which'] in ('positive'):
pass
elif resp['which'] in ('negative'):
timing_title = 'Enter new time'
timing_msg = 'Provide a new timing value '+ athlete['Name']+': '
add_time_cgi = '/cgi-bin/add_timing_data.py'

resp = app.dialogGetInput(timing_title,timing_msg).result

if resp is not None:
new_time = resp
send_to_server(web_server+add_time_cgi,{'Time':new_time,'Athlete':which_athlete})

status_update(quit_msg)
Binary file added 24-P337-sqlite-neweb/webapp/athletes.pickle
Binary file not shown.
17 changes: 17 additions & 0 deletions 24-P337-sqlite-neweb/webapp/cgi-bin/23-p319-createsimpledb.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import sqlite3

connection =sqlite3.connect('coachdata.sqlite')

cursor = connection.cursor()

cursor.execute(""" CREATE TABLE athletes (
id INTEGER PRIMARY KEY AUTOINCREMENT UNIQUE NOT NULL,
name TEXT NOT NULL,
dob DATE NOT NULL)""")
cursor.execute(""" CREATE TABLE timing_data(
athlete_id INTEGER NOT NULL,
value TEXT NOT NULL,
FOREIGN KEY (athlete_id) REFERENCES atheletes)""")
connection.commit()
connection.close()

86 changes: 86 additions & 0 deletions 24-P337-sqlite-neweb/webapp/cgi-bin/YATE.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
from string import Template
#Template 模块的相关内容,简单的字符串替换模板

def start_response(resp='text/html'):
return ('Content-type: '+ resp +'\n\n')
#一个可选的字符串作为参数,用它来创建cgi 的 content-type: 行,缺省为 text/html

def include_header(the_title):
with open('templates/header.html') as headf:
head_text = headf.read()
header = Template(head_text)
return (header.substitute(title=the_title))
#将从header.html中读入的文件,替换所提供的标题

def include_footer(the_links):
with open('templates/footer.html') as footf:
foot_text = footf.read()
link_string = ''
for key in the_links:
link_string += '<a href="'+the_links[key]+'">'+key+'</a>&nbsp;&nbsp;&nbsp;&nbsp;'
footer = Template(foot_text)
return(footer.substitute(links=link_string))
#使用一个字符串作为参数,来创建一个 html 页面的尾部,页面本身存于 footer.html 中,
#参数用于动态创建一组动态 html 链接标记,从使用来看,参数应该是一个字典

def start_form(the_url,form_type='POST'):
return('<form action="'+the_url+'" method="'+form_type+'">')
#返回表单最前面的HTML, 允许调用者制定URL,(表单数据将发送到这个URL)
#还可以指定所要使用的方法


def end_form(submit_msg="Submit"):
return('<p></p><input type=submit value="'+submit_msg+'"></form>')
#返回表单末尾的html标记,同事允许定制submit按钮的文本

def radio_button(rb_name,rb_value):
return('<input type="radio" name="'+rb_name+
'" value="'+rb_value+'">'+ rb_value+'<br/>')
#给定一个单选按钮的名和值,创建一个html 单选按钮,两个参数都是必须的


def raido_button_id(rb_name,rb_value,rb_id):
return('<input type="radio" name="'+rb_name+
'" value="'+str(rb_id)+'">'+rb_value+'<br/>')
#重新创建单选按钮,为她提供和文本不同的值

def u_list(items):
u_string = '<ul>'
for item in items:
u_string += '<li>' +item +'</li>'
u_string += '</ul>'
return(u_string)
# 给定一个项列表,将其转化为一个html 列表,每次迭代会像ul增加一个li元素

def header(header_text,header_level=2):
return ('<h'+str(header_level)+'>'+header_text+
'</h'+str(header_level)+'>')
#返回一个 html 标题标记,默认为2级标题

def para(para_text):
return('<p>'+para_text+'</p>')
#段落标记一个文本段



def create_inputs(inputs_list):
html_inputs = ''
for each_input in inputs_list:
html_inputs = html_inputs + '<input type ="Text" name="'+\
each_input + '" size=40>'
return (html_inputs)

def do_form(name, the_inputs,method='POST',text='Submit'):
with open ('templates/form.html') as formf:
form_text=formf.read()
inputs = create_inputs(the_inputs)
form = Template(form_text)

return(form.substitute(cgi_name=name,http_method = method,list_of_inputs=inputs,submit_text=text))







34 changes: 34 additions & 0 deletions 24-P337-sqlite-neweb/webapp/cgi-bin/add_timing_data.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import cgi
import os
import time
import sys
import YATE
import sqlite3

print (YATE.start_response('text/plain'))
addr = os.environ['REMOTE_ADDR']
host = os.environ['REMOTE_HOST']
method = os.environ['REQUEST_METHOD']
cur_time = time.asctime(time.localtime())

print (host+", "+addr+", "+cur_time+": "+method, file=sys.stderr)

form_data = cgi.FieldStorage()
the_id = form_data['Athlete'].value
the_time = form_data['Time'].value

connection = sqlite3.connect('coachdata.sqlite')
cursor = connection.cursor()
cursor.execute("INSERT INTO timing_data (athlete_id,value) VALUES (?,?)",
(the_id, the_time))
"""
for each_form_item in form.keys():
print (each_form_item + '->' + form[each_form_item].value,
end=' ', file=sys.stderr)
print (file = sys.stderr) #在标准错误输出上换行
"""
connection.commit()
connection.close()
print ('OK.')


34 changes: 34 additions & 0 deletions 24-P337-sqlite-neweb/webapp/cgi-bin/athletelist.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
class AthleteList(list): #新的AthleteList 类,继承了原有的list类,包含了原list的所有方法 append,extend
def __init__(self,a_name,a_dob=None,a_times=[]):
list.__init__([])
self.name = a_name
self.dob = a_dob
self.extend(a_times)
@property
def top3(self):
return(sorted(set([sanitize(t) for t in self]))[0:3])
@property
def clean_data(self):
return(sorted(set([sanitize(t) for t in self])))


def sanitize(time_string): #序列化得到的无规则数据,将其格式化为 mins.secs 的格式
if '-' in time_string:
splitter = '-'
elif ':' in time_string:
splitter = ':'
else:
return(time_string)
(mins,secs)=time_string.split(splitter)
return(mins+'.'+secs)

def load_from_file(filename): #读取文件的一行(这个文件只有一行,多行咋办)
try:
with open (filename) as f:
data = f.readline()
templ = data.strip().split(',')
return (Athlete(templ.pop(0),templ.pop(0),templ))#返回一个Athlete对象,这里已经pop了两次,所以返回值里只有times了
except IOError as err:
print('File Error: '+str(err))
return (None)

Loading

0 comments on commit 496274a

Please sign in to comment.