def GET():
web.header('Content-Type', 'text/html')
# connect to docker
try:
d_client = docker.from_env()
except Exception as e: # pragma: no cover
return (False, 'unable to connect to docker because: ' + str(e))
# start container to get network interfaces
nics = ""
try:
nics = d_client.containers.run('cyberreboot/gonet',
network_mode='host')
except Exception as e: # pragma: no cover
return (False, "Failure: " + str(e))
return (True, nics)
python类header()的实例源码
def GET(self, *args):
dir, name = args[-2:]
dir_path = 'templates/%s/' %dir
ext = name.split(".")[-1]
cType = {
"css": "text/css",
"png": "images/png",
"jpg": "images/jpeg",
"gif": "images/gif",
"ico": "images/x-icon",
"js" : "text/javascrip",
}
if name in os.listdir(dir_path):
web.header("Content-Type", cType[ext])
file_path = '%s/%s' %(dir_path, name)
return open(file_path, "rb").read()
else:
raise web.notfound()
def POST(self):
form = myform()
if not form.validates():
return render.formtest(form)
else:
# form.d.boe and form['boe'].value are equivalent ways of
# extracting the validated arguments from the form.
global question
global answer
global chat_history
global after_question
question = form['??'].value
after_question = stopwords.eliminate_stop_words(question)
answer = robot.chat(after_question)
chat_history.append(question)
chat_history.append(answer)
if answer is "":
raise web.seeother('/add')
web.header('Content-Type','text/html; charset=utf-8', unique=True) # let the browser use the utf-8 encoding
form['??'].set_value('')
return render.answer(answer,chat_history, form)
# return "Grrreat success! boe: %s, bax: %s, area: %s" % (form.d.boe, form['bax'].value, form['moe'].value)
def GET(self):
# one ip can start one game at time
ip = web.ctx.ip
try:
service = Game.manager.get_service_by_key(ip)
except KeyError:
# register game service
Game.manager.register_service(ip)
service = Game.manager.get_service_by_key(ip)
# get players' names
data = web.input()
players_names = [data[str(x)] for x in range(len(data))]
# init game service
service.init_game(players_names)
messages = [service.map_describe()]
response = {
'current_player': json.loads(json.dumps(service.current_player,cls=PlayerEncoder)),
'messages': messages
}
web.header('Content-Type', 'application/json')
return json.dumps(response)
def GET(self, uid):
user = {}
callback = web.input().get("jsonp")
try:
user = models.user(uid).load()
# JS is bad at numbers
user["id64"] = str(user["id64"])
except: pass
web.header("Content-Type", jsonMimeType)
jsonobj = json.dumps(user)
if not callback:
return jsonobj
else:
return callback + '(' + jsonobj + ');'
def GET(self, group):
obj = {}
try:
memkey = "groupstats-" + str(group)
obj = cache.get(memkey)
if not obj:
parser = group_member_page_parser(group)
obj = {}
obj["memberCount"] = parser.get_member_count()
obj["memberListShort"] = parser.get_member_list_short()
obj["logo"] = parser.get_logo()
obj["name"] = parser.get_name()
obj["abbreviation"] = parser.get_abbreviation()
cache.set(memkey, obj, time = config.ini.getint("cache", "group-stats-expiry"))
except:
pass
web.header("Content-Type", jsonMimeType)
return json.dumps(obj)
def GET(self, app, sid):
try:
user, pack = models.load_inventory(sid, scope = app)
items = pack["items"].values()
sorter = views.sorting(items)
items = sorter.sort(web.input().get("sort", sorter.byTime))
cap = config.ini.getint("rss", "inventory-max-items")
if cap: items = items[:cap]
web.header("Content-Type", "application/rss+xml")
return _feed_renderer.inventory_feed(app, user, items)
except (steam.user.ProfileError, steam.items.InventoryError, steam.api.HTTPError) as E:
raise rssNotFound()
except Exception as E:
log.main.error(str(E))
raise rssNotFound()
def sendoutput(self, result):
content = result.read()
logger.debug(content)
if result.status == 200:
web.ctx.headers = result.getheaders()
if len(content.strip()) > 0:
d = self.parse_response(content)
err = d.find('err')
if err is not None:
reason = '%s %s' % (err.attrib['code'], err.attrib['msg'])
response = {'error': reason}
web.ctx.status = str(400)+' '+reason
else:
response = {'id': d.findtext('statusid')}
content = simplejson.dumps(response)
filtered = self.filter(content)
web.header('content-length', len(filtered))
return filtered
else:
web.ctx.headers = result.getheaders()
web.ctx.status = str(result.status)+' '+result.reason
return content
app.py 文件源码
项目:candidate-selection-tutorial
作者: candidate-selection-tutorial-sigir2017
项目源码
文件源码
阅读 18
收藏 0
点赞 0
评论 0
def search_simple_index(query, offset, count, draw):
"""
This function is responsible for hitting the solr endpoint
and returning the results back.
"""
results = SOLR_SIMPLEINDEX.search(q=query, **{
'start': int(offset),
'rows': int(count)
})
print("Saw {0} result(s) for query {1}.".format(len(results), query))
formatted_hits = []
for hit in results.docs:
formatted_hits.append(
[hit['_news_title'], hit['_news_publisher'], CATEGORY[hit['_news_category'][0]], hit['_news_url']])
response = {'draw': draw,
'recordsFiltered': results.hits,
'data': formatted_hits}
web.header('Content-Type', 'application/json')
return json.dumps(response)
app.py 文件源码
项目:candidate-selection-tutorial
作者: candidate-selection-tutorial-sigir2017
项目源码
文件源码
阅读 16
收藏 0
点赞 0
评论 0
def search_entity_aware_index(query, offset, count, draw, qf):
"""
This function is responsible for hitting the solr endpoint
and returning the results back.
"""
results = SOLR_ENTITYAWAREINDEX.search(q=query, **{
'start': int(offset),
'rows': int(count),
'qf': qf
})
print("Saw {0} result(s) for query {1}.".format(len(results), query))
formatted_hits = []
for hit in results.docs:
formatted_hits.append(
[hit['_news_title'], hit['_news_publisher'], CATEGORY[hit['_news_category'][0]], hit['_news_url']])
response = {'draw': draw,
'recordsFiltered': results.hits,
'data': formatted_hits}
web.header('Content-Type', 'application/json')
return json.dumps(response)
app.py 文件源码
项目:candidate-selection-tutorial
作者: candidate-selection-tutorial-sigir2017
项目源码
文件源码
阅读 18
收藏 0
点赞 0
评论 0
def search(query, offset, count, draw, solr_endpoint):
"""
This function is responsible for hitting the solr endpoint
and returning the results back.
"""
results = solr_endpoint.search(q=query, **{
'start': int(offset),
'rows': int(count)
})
print("Saw {0} result(s) for query {1}.".format(len(results), query))
formatted_hits = []
for hit in results.docs:
formatted_hits.append(
[hit['_news_title'], hit['_news_publisher'], CATEGORY[hit['_news_category'][0]], hit['_news_url']])
response = {'draw': draw,
'recordsFiltered': results.hits,
'data': formatted_hits}
web.header('Content-Type', 'application/json')
return json.dumps(response)
app.py 文件源码
项目:candidate-selection-tutorial
作者: candidate-selection-tutorial-sigir2017
项目源码
文件源码
阅读 16
收藏 0
点赞 0
评论 0
def search_simple_index(query, offset, count, draw):
"""
This function is responsible for hitting the solr endpoint
and returning the results back.
"""
results = SOLR_SIMPLEINDEX.search(q=query, **{
'start': int(offset),
'rows': int(count),
'cache': 'false'
})
print("Saw {0} result(s) for query {1}.".format(len(results), query))
formatted_hits = []
for hit in results.docs:
formatted_hits.append(
[hit['_news_title'], hit['_news_publisher'], CATEGORY[hit['_news_category'][0]], hit['_news_url']])
response = {'draw': draw,
'recordsFiltered': results.hits,
'data': formatted_hits}
web.header('Content-Type', 'application/json')
return json.dumps(response)
def POST(self, o_type):
web.header('Access-Control-Allow-Origin', self.allow_origin)
web.header('Access-Control-Allow-Headers', "Content-type")
data = web.data()
payload = {}
try:
payload = ast.literal_eval(data)
if type(payload) != dict:
payload = ast.literal_eval(json.loads(data))
except:
return "malformed json body"
client_session_id = uuid.uuid4().hex
out = ""
if o_type == 'a':
out = self.INDEX_HTML%(client_session_id, payload) + \
self.INDEX_HTML_TYPE_A + \
self.INDEX_HTML_END
elif o_type == 'b':
out = self.INDEX_HTML%(client_session_id, payload) + \
self.INDEX_HTML_TYPE_B + \
self.INDEX_HTML_END
return out
def GET(self):
web.header('Access-Control-Allow-Origin', self.allow_origin)
web.header("Content-Type","text/yaml")
try:
with open("swagger.yaml", 'r') as f:
filedata = f.read()
newdata = filedata.replace("mydomain", self.rest_url)
with open("swagger.yaml", 'w') as f:
f.write(newdata)
f = open("swagger.yaml", 'r')
except:
try:
with open("../vcontrol/swagger.yaml", 'r') as f:
filedata = f.read()
newdata = filedata.replace("mydomain", self.rest_url)
with open("../vcontrol/swagger.yaml", 'w') as f:
f.write(newdata)
f = open("../vcontrol/swagger.yaml", 'r')
except:
# using python path, don't allow write-back
pass
return f.read()
def POST(self, machine):
web.header('Access-Control-Allow-Origin', self.allow_origin)
# TODO how does this work with swagger?
x = web.input(myfile={})
filedir = '/tmp/templates/'+machine # change this to the directory you want to store the file in.
try:
if not os.path.exists(filedir):
os.makedirs(filedir)
if 'myfile' in x: # to check if the file-object is created
filepath=x.myfile.filename.replace('\\','/') # replaces the windows-style slashes with linux ones.
filename=filepath.split('/')[-1] # splits the and chooses the last part (the filename with extension)
fout = open(filedir +'/'+ filename,'w') # creates the file where the uploaded file should be stored
fout.write(x.myfile.file.read()) # writes the uploaded file to the newly created file.
fout.close() # closes the file, upload complete.
# copy file to vent instance
cmd = "docker-machine scp "+filedir+"/"+filename+" "+machine+":/var/lib/docker/data/templates/"
output = subprocess.check_output(cmd, shell=True)
# remove file from vcontrol-daemon
output = subprocess.check_output("rm -f "+filedir+"/"+filename, shell=True)
return "successfully deployed", filename, "to", str(machine)
except Exception as e:
return "failed to deploy to", str(machine), str(e)
return "failed to deploy to", str(machine)
def GET(self, machine, o_type):
web.header('Access-Control-Allow-Origin', self.allow_origin)
# !! TODO handle data later
# !! TODO test with swagger
#if 'no_cache' in data:
# if not data['no_cache']:
# cmd += " --no-cache"
client_session_id = uuid.uuid4().hex
out = ""
if o_type == 'a':
out = self.INDEX_HTML%(machine, client_session_id) + \
self.INDEX_HTML_TYPE_A + \
self.INDEX_HTML_END
elif o_type == 'b':
out = self.INDEX_HTML%(machine, client_session_id) + \
self.INDEX_HTML_TYPE_B + \
self.INDEX_HTML_END
return out
def POST(self, machine):
web.header('Access-Control-Allow-Origin', self.allow_origin)
data = web.data()
payload = {}
try:
payload = ast.literal_eval(data)
if type(payload) != dict:
payload = ast.literal_eval(json.loads(data))
except:
return "malformed json body"
try:
command = payload['command']
except:
out = "you must specify a command"
return out
try:
cmd = "/usr/local/bin/docker-machine ssh "+machine+" \""+command+"\""
out = subprocess.check_output(cmd, shell=True)
except:
out = "unable to execute generic command"
return str(out)
def POST(self):
web.header('Access-Control-Allow-Origin', self.allow_origin)
web.header('Access-Control-Allow-Headers', "Content-type")
# !! TODO does this work with swagger?
data = web.data()
payload = {}
try:
payload = ast.literal_eval(data)
if type(payload) != dict:
payload = ast.literal_eval(json.loads(data))
except Exception as e:
return "malformed json body", str(e)
try:
filedir = '/tmp/templates/'+payload['machine']
if not os.path.exists(filedir):
os.makedirs(filedir)
cmd = "docker-machine scp "+payload['machine']+":/var/lib/docker/data/templates/"+payload['template']+" "+filedir
output = subprocess.check_output(cmd, shell=True)
f = open(filedir+"/"+payload['template'], 'rb')
return f.read()
except Exception as e:
return "failed to download", str(e)
return "failed to download", str(e)
def POST(self, machine):
web.header('Access-Control-Allow-Origin', self.allow_origin)
# TODO how does this work with swagger?
x = web.input(myfile={})
filedir = '/tmp/files/'+machine # change this to the directory you want to store the file in.
try:
if not os.path.exists(filedir):
os.makedirs(filedir)
if 'myfile' in x: # to check if the file-object is created
filepath=x.myfile.filename.replace('\\','/') # replaces the windows-style slashes with linux ones.
filename=filepath.split('/')[-1] # splits the and chooses the last part (the filename with extension)
fout = open(filedir +'/'+ filename,'w') # creates the file where the uploaded file should be stored
fout.write(x.myfile.file.read()) # writes the uploaded file to the newly created file.
fout.close() # closes the file, upload complete.
# copy file to vent instance
cmd = "docker-machine scp "+filedir+"/"+filename+" "+machine+":/files/"
output = subprocess.check_output(cmd, shell=True)
# remove file from vcontrol-daemon
output = subprocess.check_output("rm -f "+filedir+"/"+filename, shell=True)
return "successfully uploaded", filename, "to", str(machine)
except Exception as e:
return "failed to upload to", str(machine), str(e)
return "failed to upload to", str(machine)
def GET(self, provider):
try:
web.header('Access-Control-Allow-Origin', self.allow_origin)
except Exception as e:
print(e.message)
open_d = os.environ.get('VCONTROL_OPEN')
providers_file_path = os.path.join(os.path.dirname(__file__), 'providers.txt')
if web.ctx.env["HTTP_HOST"] == 'localhost:8080' or open_d == "true":
f = open(providers_file_path,"r")
lines = f.readlines()
f.close()
flag = 0
with open(providers_file_path, 'w') as f:
for line in lines:
if not line.startswith(provider+":"):
f.write(line)
else:
flag = 1
if flag:
return "removed " + provider
else:
return provider + " not found, couldn't remove"
else:
return "must be done from the localhost running vcontrol daemon"
def GET(self):
""" GET HTTP Request """
try:
web.header('Access-Control-Allow-Origin', self.allow_origin)
except Exception as e:
print(e.message)
try:
providers = {}
providers_file_path = os.path.join(os.path.dirname(__file__), 'providers.txt')
if os.path.isfile(providers_file_path):
with open(providers_file_path, 'r') as f:
for line in f:
providers[line.split(":")[0]] = line.split(":")[1].strip()
return providers
except:
return "unable to get providers"
def GET():
web.header('Content-Type', 'text/html')
# connect to docker
try:
containers = docker.from_env()
except Exception as e: # pragma: no cover
return (False, 'unable to connect to docker because: ' + str(e))
# search for all docker containers and grab ncapture containers
container_list = []
try:
for c in containers.containers.list(all=True):
# TODO: maybe find a way to not have to hard code image name
if c.attrs["Config"]["Image"] == \
"cyberreboot/vent-ncapture:master":
# the core container is not what we want
if "core" not in c.attrs["Config"]["Labels"]\
["vent.groups"]:
lst = {}
lst['id'] = c.attrs["Id"][:12]
lst['status'] = c.attrs["State"]["Status"]
lst['args'] = c.attrs['Args']
container_list.append(lst)
except Exception as e: # pragma: no cover
return (False, "Failure: " + str(e))
return (True, container_list)
def POST():
"""
Send a POST request with a docker container ID and it will be stopped.
Example input: {'id': "12345"}, {'id': ["123", "456"]
"""
web.header('Content-Type', 'application/json')
# verify user input
data = web.data()
payload = {}
try:
payload = ast.literal_eval(data)
except Exception as e: # pragma: no cover
return (False, 'malformed payload : ' + str(e))
# verify payload has a container ID
if 'id' not in payload:
return (False, 'payload missing container id')
# connect to docker and stop the given container
c = None
try:
c = docker.from_env()
except Exception as e: # pragma: no cover
return (False, 'unable to connect to docker because: ' + str(e))
# stop containers chosen from CLI
try:
for container_id in payload['id']:
c.containers.get(container_id).stop()
except Exception as e: # pragma: no cover
return (False, 'unable to stop list of containers because: ' +
str(e))
return (True, 'container successfully stopped: ' + str(payload['id']))
def POST():
"""
Send a POST request with a docker container ID and it will be deleted.
Example input: {'id': "12345"}, {'id': ["123", "456"]}
"""
web.header('Content-Type', 'application/json')
# verify user input
data = web.data()
payload = {}
try:
payload = ast.literal_eval(data)
except Exception as e: # pragma: no cover
return (False, 'malformed payload : ' + str(e))
# verify payload has a container ID
if 'id' not in payload:
return (False, 'payload missing container id')
# connect to docker and stop the given container
c = None
try:
c = docker.from_env()
except Exception as e: # pragma: no cover
return (False, 'unable to connect to docker because: ' + str(e))
# delete containers chosen from CLI
try:
for container_id in payload['id']:
c.containers.get(container_id).remove()
except Exception as e: # pragma: no cover
return (False, 'unable to delete containers because: '
+ str(e))
return (True, 'container successfully deleted: ' + str(payload['id']))
def POST():
"""
Send a POST request with a docker container ID and it will be started.
Example input: {'id': "12345"}, {'id': ["123", "456"]}
"""
web.header('Content-Type', 'application/json')
# verify user input
data = web.data()
payload = {}
try:
payload = ast.literal_eval(data)
except Exception as e: # pragma: no cover
return (False, 'malformed payload : ' + str(e))
# verify payload has a container ID
if 'id' not in payload:
return (False, 'payload missing container id')
# connect to docker and stop the given container
c = None
try:
c = docker.from_env()
except Exception as e: # pragma: no cover
return (False, 'unable to connect to docker because: ' + str(e))
# start containers chosen from CLI
try:
for container_id in payload['id']:
c.containers.get(container_id).start()
except Exception as e: # pragma: no cover
return (False, 'unable to start list of containers because: ' +
str(e))
return (True, 'container successfully started: ' + str(payload['id']))
def set_json_response():
"""
????content-type?json
:return:
"""
web.header('content-type', 'application/json;charset=utf-8', unique=True)
def getHeader(self):
header = {}
header['logoText'] = self.title
modules = []
return header
def GET( self, x ):
print 'in structure: '+x
web.header('Content-Type', 'application/json')
layout = portal_pages[x]
return '{"layout":'+ layout.to_JSON() +'}'
def _make_response(self, content, headers, status):
web.ctx.status = status
for k, v in headers:
web.header(k, v)
return content
def GET(self):
web.header('Content-Type', "application/json")
return json.dumps({'status': 'ok'})