def route():
args = request.json
args = args if args else {}
cfg = args.get('cfg', None)
log_request(
args.get('user', 'unknown'),
args.get('hostname', 'unknown'),
request.remote_addr,
request.method,
request.path,
args)
try:
endpoint = create_endpoint(request.method, cfg, args)
json, status = endpoint.execute()
except AutocertError as ae:
status = 500
json = dict(errors={ae.name: ae.message})
return make_response(jsonify(json), status)
if not json:
raise EmptyJsonError(json)
return make_response(jsonify(json), status)
python类route()的实例源码
def route(self, rule, **options):
app = self.app
url_map = self.url_map
url_map[URL_PREFIX + rule] = True
def decorator(func):
@app.route(URL_PREFIX + rule, **options)
@wraps(func)
def wrapper(username, name, *args, **kw):
repo = repos_service.get(username, name)
if repo is None:
return abort(404)
ctx = RepositoryContext(url_map, repo)
return func(ctx, *args, **kw)
return wrapper
return decorator
def meraki():
udata = {}
udata['grant_url'] = request.args.get('base_grant_url')
# udata['continue_url'] = request.args.get('user_continue_url')
udata['continue_url'] = 'http://wait.thekey.pw/guest/2342423'
udata['node_mac'] = request.args.get('node_mac')
udata['client_ip'] = request.args.get('client_ip')
udata['client_mac'] = request.args.get('client_mac')
udata['redirect_url'] = str(udata['grant_url']) + str("?continue_url=") + str(udata['continue_url'] + "&duration=300")
services = db.session.query(Service).all()
guest = db.session.query(Guest).filter_by(guest_mac=udata['client_mac']).first()
return render_template('guest/portal.html', data=udata, services=services, guest=guest)
# @app.route("/sms", methods=['POST'])
def lang(code):
"""
Changes the language of the app for a given session
:param code: the language code (e.g: pt-BR)
:return: just a generic String (it is mandatory to return something in route functions)
"""
if code in LANGUAGES:
session['lang'] = code
return 'Changed language to: ' + code
def search1():
origin = request.args.get('origin', "", type=str)
destination = request.args.get('destination', "", type=str)
originGeo = PlaceDetails(origin)
destinationGeo = PlaceDetails(destination)
restaurants = FindRestaurants(origin, destination)
waypoints = route.best_path(restaurants, originGeo, destinationGeo)
print 'waypoints: ' + str(waypoints)
directions = NewDir(origin, destination, waypoints)
print 'directions: ' + str(directions)
return jsonify(directions)
def redirect_url(default='index'):
return request.args.get('next') or \
request.referrer or \
url_for(default)
# Robots.txt & sitemap static route for indexing.
# Both files can be placed in app/static
def chat():
global thread
if thread is None:
print 'started'
thread = Thread(target=background_thread)
thread.daemon = True
thread.start()
return render_template('chat.html')
# @app.route('/poll', methods=['POST'])
def index():
# This route is mandatory for the load balancer
return Response(json.dumps({'result': 'OK'}, cls=CustomJSONEncoder), status=200, mimetype="application/json")
def entry_css(path):
print(path)
return flask.send_from_directory(DIST_DIR, path)
# @app.route('/index.html', methods=['GET'])
# def entry_js():
# return flask.send_from_directory(DIST_DIR, 'index.js', mimetype='text/javascript')
#
#
# @app.route('/0.async.js', methods=['GET'])
# def entry_0_async_js():
# return flask.send_from_directory(DIST_DIR, '0.async.js', mimetype='text/javascript')
def allowed_file(filename):
return '.' in filename and filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS
# Login Handling
#@app.route('/register', methods=['GET', 'POST'])
def upload():
print('Hello world!')
# Get the name of the uploaded file
#file = request.files['uploadFile']
file = request.files['uploadFile']
# Check if the file is one of the allowed types/extensions
if file and allowed_file(file.filename):
# Make the filename safe, remove unsupported chars
filename = secure_filename(file.filename)
# Move the file form the temporal folder to
# the upload folder we setup
print("filename: ", filename)
print("file: ", file)
filepath=os.path.join(app.config['UPLOAD_FOLDER'], filename)
file.save(filepath)
return findSimilar(imagename=filename)
# This route is expecting a parameter containing the name
# of a file. Then it will locate that file on the upload
# directory and show it on the browser, so if the user uploads
# an image, that image is going to be show after the upload
#@app.route('/uploads/<filename>')
#def get_uploadedFile(filename):
# return send_from_directory(app.config['UPLOAD_FOLDER'], filename)
# @app.route('/uploads')
# def uploads():
# return render_template('uploads.html')
def handle_reviews(user_id):
'''Returns the reviews of the user passed the argument `user_id`. This is
accomplished through querying the ReviewUser table, and returning rows in
which `user_id` is equal to the id of a user. Then, using the
ForeignKeyField, retrieve those particular reviews with the to_dict()
method. Will not add attributes `updated_at` or `created_at`. Note: this
route is for reviewing the user with id `user_id`. The user id passed as
a parameter with a POST request is the user making the review.
Keyword arguments:
user_id = The id of the user that is being reviewed.
'''
try:
User.select().where(User.id == user_id).get()
except User.DoesNotExist:
return jsonify(msg="There is no user with this id."), 404
if request.method == 'GET':
arr = []
for review_user in (ReviewUser
.select()
.where(ReviewUser.user == user_id)):
arr.append(review_user.review.to_dict())
return jsonify(arr), 200
elif request.method == 'POST':
params = request.values
review = Review()
'''Check that all the required parameters are made in request.'''
required = set(["message", "user"]) <= set(request.values.keys())
if required is False:
return jsonify(msg="Missing parameter."), 400
for key in params:
if key == 'updated_at' or key == 'created_at':
continue
setattr(review, key, params.get(key))
if review.message is None or review.user_id is None:
return jsonify(msg="Missing required data."), 404
review.save()
'''Save the connection in the ReviewUser table.'''
ReviewUser().create(user=user_id, review=review.id)
return jsonify(review.to_dict()), 201
def message():
#body_mes = client.messages.Body
resp = twilio.twiml.Response()
resp.message("Thanks, expect a call soon!")
messages = deque(client.messages.list())
last_message = messages.popleft()
last_text = last_message.body
phone_number = last_message.from_
f = open('phonenumber.txt', 'w')
f.write(phone_number)
list_of_tuples = get_sent_tuples(parse_string(str(last_text)))
# print list_of_tuples
list_of_chords=get_chords(list_of_tuples)
# print list_of_chords
print "test"
abcstring=simpleasabc(list_of_chords)
print "test1"
myabcfile=open("app/PySynth/abcsheet.abc.txt",'w')
myabcfile.write(abcstring)
myabcfile.close()
os.chdir("/Users/Meg/Documents/Hackathons/uncommonhacks/app/PySynth")
# command = "cd"
# process = subprocess.Popen(command.split(), stdout=subprocess.PIPE)
# print process.communicate()[0]
# command = "cd PySynth"
# process = subprocess.Popen(command.split(), stdout=subprocess.PIPE)
# print process.communicate()[0]
command = "python wavesdontdie.py abcsheet.abc.txt"
process = subprocess.Popen(command.split(), stdout=subprocess.PIPE)
print process.communicate()[0]
os.chdir("/Users/Meg/Documents/Hackathons/uncommonhacks")
f = open('phonenumber.txt', 'r')
phone_number = f.read()
call = client.calls.create(url="http://twimlbin.com/23667f37ab8451dbb3223f51d2248f21",
to=phone_number,
from_="+16307556548")
return str(resp)
# @app.route("/makecall", methods=['GET', 'POST'])
# def makecall():
# f = open('phonenumber.txt', 'r')
# phone_number = f.read()
# call = client.calls.create(url="http://twimlbin.com/23667f37ab8451dbb3223f51d2248f21",
# to=phone_number,
# from_="+16307556548")
# return "working"
def selfmanagement():
if request.method == 'POST':
u = get_user_by_name(session.get('name'))
if not bcrypt.checkpw(request.form['password_old'], u.password):
success = "Passwort falsch!"
else:
if len(request.form['password1']) > 0:
if ('password1' in request.form) & ('password2' in request.form):
if (request.form['password1'] == request.form['password2']):
u.password = bcrypt.hashpw(request.form['password1'], bcrypt.gensalt())
u.rfid_id = request.form['rfid_id']
if 'onlyrfid' in request.form:
u.onlyrfid = True
else:
u.onlyrfid = False
update_user(u)
success = u'Einstellungen wurden übernommen!'
else:
success = u'Neue Passwörter stimmen nicht überein!'
else:
u.rfid_id = request.form['rfid_id']
if 'onlyrfid' in request.form:
u.onlyrfid = True
else:
u.onlyrfid = False
update_user(u)
success = u'Einstellungen wurden übernommen!'
return render_template('selfmanagement.html', success=success, user=get_user_by_name(session.get('name')))
if request.method == 'GET':
return render_template('selfmanagement.html', user=get_user_by_name(session.get('name')))
#migrate the db to hashed passwords
#@app.route('/hashdb')
#@requires_baron
#def hashdb():
# users = get_users()
# for user in users:
# user.password = bcrypt.hashpw(user.password, bcrypt.gensalt())
# update_user(user)
# return render_template('index.html', users=users, user=get_user_by_name(session.get('name')))
def handle_reviews(user_id):
'''Returns the reviews of the user passed the argument `user_id`. This is
accomplished through querying the ReviewUser table, and returning rows in
which `user_id` is equal to the id of a user. Then, using the
ForeignKeyField, retrieve those particular reviews with the to_dict()
method. Will not add attributes `updated_at` or `created_at`. Note: this
route is for reviewing the user with id `user_id`. The user id passed as
a parameter with a POST request is the user making the review.
Keyword arguments:
user_id = The id of the user that is being reviewed.
'''
try:
User.select().where(User.id == user_id).get()
except User.DoesNotExist:
return jsonify(msg="There is no user with this id."), 404
if request.method == 'GET':
arr = []
for review_user in (ReviewUser
.select()
.where(ReviewUser.user == user_id)):
arr.append(review_user.review.to_dict())
return jsonify(arr), 200
elif request.method == 'POST':
params = request.values
review = Review()
'''Check that all the required parameters are made in request.'''
required = set(["message", "user"]) <= set(request.values.keys())
if required is False:
return jsonify(msg="Missing parameter."), 400
for key in params:
if key == 'updated_at' or key == 'created_at':
continue
setattr(review, key, params.get(key))
if review.message is None or review.user_id is None:
return jsonify(msg="Missing required data."), 404
review.save()
'''Save the connection in the ReviewUser table.'''
ReviewUser().create(user=user_id, review=review.id)
return jsonify(review.to_dict()), 201