In [1]:
import math
def plot3d(myFile, directory, name):
fname = name.split('.')
out = fname[0]
fnodes = absDir + '\\' + out + 'nodes.csv'
fedges = absDir + '\\' + out + 'edges.csv'
files = [fnodes, fedges]
points = []
# filename = inpath + f + '.csv'
# nodename = outpath + f + '.r25.nodes.csv'
# edgename = outpath + f + '.r25.edges.csv'
# with open(sys.argv[1], 'r') as infile:
# with open(filename, 'r') as infile:
for line in myFile:
line = line.strip().split(',')
points.append(str(line[0]) + "," + str(line[1]) + "," + str(line[2]))
# with open(sys.argv[2], 'w') as outfile:
# with open(nodename, 'w') as outfile:
# with open(sys.argv[3], 'w') as edgefile:
# with open(edgename, 'w') as edgefile:
with open(fnodes, 'w') as nodes:
with open(fedges, 'w') as edges:
for ind in range(len(points)):
temp = points[ind].strip().split(',')
x = temp[0]
y = temp[1]
z = temp[2]
radius = 25
nodes.write("s" + str(ind + 1) + "," + str(x) + "," + str(y) + "," + str(z) + "\n")
for index in range(ind + 1, len(points)):
tmp = points[index].strip().split(',')
distance = math.sqrt(math.pow(int(x) - int(tmp[0]), 2) + math.pow(int(y) - int(tmp[1]), 2) + math.pow(int(z) - int(tmp[2]), 2))
if distance < radius:
edgeweight = math.exp(-1 * distance)
edges.write("s" + str(ind + 1) + "," + "s" + str(index + 1) + "," + str(edgeweight) + "\n")
return files
In [ ]:
import os, os.path
import random
import sqlite3
import string
import time
import cherrypy
DB_STRING = "my.db"
class StringGenerator(object):
@cherrypy.expose
def index(self):
return open('index.html')
@cherrypy.expose
class StringGeneratorWebService(object):
@cherrypy.tools.accept(media='text/plain')
def GET(self):
with sqlite3.connect(DB_STRING) as c:
cherrypy.session['ts'] = time.time()
r = c.execute("SELECT value FROM user_string WHERE session_id=?",
[cherrypy.session.id])
return r.fetchone()
def POST(self, length=8):
some_string = ''.join(random.sample(string.hexdigits, int(length)))
with sqlite3.connect(DB_STRING) as c:
cherrypy.session['ts'] = time.time()
c.execute("INSERT INTO user_string VALUES (?, ?)",
[cherrypy.session.id, some_string])
return some_string
def PUT(self, another_string):
with sqlite3.connect(DB_STRING) as c:
cherrypy.session['ts'] = time.time()
c.execute("UPDATE user_string SET value=? WHERE session_id=?",
[another_string, cherrypy.session.id])
def DELETE(self):
cherrypy.session.pop('ts', None)
with sqlite3.connect(DB_STRING) as c:
c.execute("DELETE FROM user_string WHERE session_id=?",
[cherrypy.session.id])
def setup_database():
"""
Create the `user_string` table in the database
on server startup
"""
with sqlite3.connect(DB_STRING) as con:
con.execute("CREATE TABLE user_string (session_id, value)")
def cleanup_database():
"""
Destroy the `user_string` table from the database
on server shutdown.
"""
with sqlite3.connect(DB_STRING) as con:
con.execute("DROP TABLE user_string")
if __name__ == '__main__':
conf = {
'/': {
'tools.sessions.on': True,
'tools.staticdir.root': os.path.abspath(os.getcwd())
},
'/generator': {
'request.dispatch': cherrypy.dispatch.MethodDispatcher(),
'tools.response_headers.on': True,
'tools.response_headers.headers': [('Content-Type', 'text/plain')],
},
'/static': {
'tools.staticdir.on': True,
'tools.staticdir.dir': './public'
}
}
cherrypy.engine.subscribe('start', setup_database)
cherrypy.engine.subscribe('stop', cleanup_database)
webapp = StringGenerator()
webapp.generator = StringGeneratorWebService()
cherrypy.quickstart(webapp, '/', conf)
In [ ]:
"""
Tutorial: File upload and download
Uploads
-------
When a client uploads a file to a CherryPy application, it's placed
on disk immediately. CherryPy will pass it to your exposed method
as an argument (see "myFile" below); that arg will have a "file"
attribute, which is a handle to the temporary uploaded file.
If you wish to permanently save the file, you need to read()
from myFile.file and write() somewhere else.
Note the use of 'enctype="multipart/form-data"' and 'input type="file"'
in the HTML which the client uses to upload the file.
Downloads
---------
If you wish to send a file to the client, you have two options:
First, you can simply return a file-like object from your page handler.
CherryPy will read the file and serve it as the content (HTTP body)
of the response. However, that doesn't tell the client that
the response is a file to be saved, rather than displayed.
Use cherrypy.lib.static.serve_file for that; it takes four
arguments:
serve_file(path, content_type=None, disposition=None, name=None)
Set "name" to the filename that you expect clients to use when they save
your file. Note that the "name" argument is ignored if you don't also
provide a "disposition" (usually "attachement"). You can manually set
"content_type", but be aware that if you also use the encoding tool, it
may choke if the file extension is not recognized as belonging to a known
Content-Type. Setting the content_type to "application/x-download" works
in most cases, and should prompt the user with an Open/Save dialog in
popular browsers.
"""
import os
import os.path
import cherrypy
from cherrypy.lib import static
from cherrypy.lib.static import serve_file
# import clarityviz
localDir = os.path.dirname('public')
absDir = os.path.join(os.getcwd(), localDir)
print absDir
class FileDemo(object):
@cherrypy.expose
def index(self, directory="."):
return """
<html><body>
<h2>Upload a file</h2>
<form action="upload" method="post" enctype="multipart/form-data">
filename: <input type="file" name="myFile" /><br />
<input type="submit" />
</form>
<h2>Download a file</h2>
<a href='download'>This one</a>
</body></html>
"""
@cherrypy.expose
def upload(self, myFile):
# out = """<html>
# <body>
# myFile length: %s<br />
# myFile filename: %s<br />
# myFile mime-type: %s
# </body>
# </html>"""
# Although this just counts the file length, it demonstrates
# how to read large files in chunks instead of all at once.
# CherryPy reads the uploaded file into a temporary file;
# myFile.file.read reads from that.
# size = 0
# while True:
# data = myFile.file.read(8192)
# if not data:
# break
# size += len(data)
# return out % (size, myFile.filename, myFile.content_type)
# size = 0
out = plot3d(myFile.file, absDir, myFile.filename)
# data = myFile.file.read()
# for r, line in enumerate(myFile.file):
# out += (line + "<br/>")
# size = len(data)
html = """
<html><body>
<h2>Ouputs</h2>
<a href="index?directory=%s">Up</a><br />
""" % os.path.dirname(os.path.abspath("."))
print os.path.dirname(os.path.abspath("."))
# for filename in glob.glob(directory + '/*'):
for filename in out:
# print filename
absPath = os.path.abspath(filename)
# print absPath
if os.path.isdir(absPath):
link = '<a href="/index?directory=' + absPath + '">' + os.path.basename(filename) + "</a> <br />"
html += link
# print link
else:
link = '<a href="/download/?filepath=' + absPath + '">' + os.path.basename(filename) + "</a> <br />"
html += link
# print link
html += """</body></html>"""
return html
# return out % (size, myFile.filename, myFile.content_type)
# @cherrypy.expose
# def download(self):
# path = os.path.join(absDir, 'testout.csv')
# print path
# return static.serve_file(path, 'application/x-download',
# 'attachment', os.path.basename(path))
index.exposed = True
class Download:
def index(self, filepath):
return serve_file(filepath, "application/x-download", "attachment")
index.exposed = True
tutconf = os.path.join(os.path.dirname('C:\\Users\\L\\Anaconda2\\Lib\\site-packages\\cherrypy\\tutorial\\'), 'tutorial.conf')
print tutconf
if __name__ == '__main__':
# CherryPy always starts with app.root when trying to map request URIs
# to objects, so we need to mount a request handler root. A request
# to '/' will be mapped to HelloWorld().index().
root = FileDemo()
root.download = Download()
cherrypy.quickstart(root, config=tutconf)
In [ ]:
# download tutorial
#!python
import glob
import os.path
import cherrypy
from cherrypy.lib.static import serve_file
class Root:
def index(self, directory="."):
html = """<html><body><h2>Here are the files in the selected directory:</h2>
<a href="index?directory=%s">Up</a><br />
""" % os.path.dirname(os.path.abspath(directory))
print os.path.dirname(os.path.abspath(directory))
for filename in glob.glob(directory + '/*'):
absPath = os.path.abspath(filename)
print absPath
if os.path.isdir(absPath):
directory = '<a href="/index?directory=' + absPath + '">' + os.path.basename(filename) + "</a> <br />"
html += directory
print directory
else:
link = '<a href="/download/?filepath=' + absPath + '">' + os.path.basename(filename) + "</a> <br />"
html += link
print link
html += """</body></html>"""
return html
index.exposed = True
class Download:
def index(self, filepath):
return serve_file(filepath, "application/x-download", "attachment")
index.exposed = True
if __name__ == '__main__':
root = Root()
root.download = Download()
cherrypy.quickstart(root)
In [ ]:
#!python
import os.path
import cherrypy
class Root:
@cherrypy.expose
def index(self):
return """<html>
<head>
<title>CherryPy static tutorial</title>
</head>
<html>
<body>
<a href="feed/notes.rss">RSS 2.0</a>
<br />
<a href="feed/notes.atom">Atom 1.0</a>
</body>
</html>"""
if __name__ == '__main__':
current_dir = os.path.dirname(os.path.abspath(__file__))
# Set up site-wide config first so we get a log if errors occur.
cherrypy.config.update({'environment': 'production',
'log.error_file': 'site.log',
'log.screen': True})
conf = {'/feed': {'tools.staticdir.on': True,
'tools.staticdir.dir': os.path.join(current_dir, 'feeds'),
'tools.staticdir.content_types': {'rss': 'application/xml',
'atom': 'application/atom+xml'}}}
cherrypy.quickstart(Root(), '/', config=conf)
In [ ]: