def dec(*args, **kwargs): """This decorater function will send an authenticate header, if none is present and denies access, if HTTP Digest Auth failed.""" request = flask.request usehtml = request.accept_mimetypes.accept_html if not request.authorization: response = Response('Unauthorized', 401, content_type='text/html; charset=utf-8' if usehtml else 'application/json') response.www_authenticate.set_digest( 'Application', algorithm='MD5', nonce=standard_b64encode(urandom(32)), qop=('auth', ), opaque='%x' % getrandbits(128)) return response else: account = app.db.accounts.find_one( {'email': request.authorization.username}) if account and account['activated_at'] == None: return Response('[ "Your account hasn\'t been activated. Please ' \ + 'check your email and activate your account." ]', 409) elif prove_auth(app, request) != request.authorization.response: return Response('Forbidden', 403) return f(*args, **kwargs)
def deleteProduct(self, request): """Create a new product - product data is posted as json Example request :: { "id": "1", "title": "Yamaha", "passenger_capacity": 7, "maximum_speed": 300, "in_stock": 10, "category": "Car" } The response contains the new product ID in a json document :: {message} """ schema = ProductSchema(strict=True) try: product_data = schema.loads(request.get_data(as_text=True)).data # Delete the product self.products_rpc.delete(product_data) except ValueError as exc: self.logger.info("Invalid json: {}".format(exc)) message = "Invalid json: {}".format(exc) return Response( json.dumps(RequestHandler.formatResponse(status_code=403, error='BAD_REQUEST', message=message)), mimetype='application/json') except ValidationError as exc: self.logger.info("Invalid schema: {}".format(exc)) message = "Invalid schema: {}".format(exc) return Response( json.dumps(RequestHandler.formatResponse(status_code=403, error='INVALID_SCHEMA', message=message)), mimetype='application/json') except Exception as ex: self.logger.info(ex) return Response( json.dumps(RequestHandler.formatResponse(status_code=403, error='Exception', message=str(ex))), mimetype='application/json') return Response( json.dumps(RequestHandler.formatResponse(status_code=200, message='Delete successful')), mimetype='application/json' )
def application(request): if request.method == 'POST': return Response(repr(request.files) + "\n" + repr(request.form), status=500) return Response( '<form action="" method="post" enctype="multipart/form-data"><input type="file" name="f"><input type="submit" value="Upload"></form>', mimetype='text/html')
def showCart(self, request): """Gets the order details for the orders given by `hashed_order_ids`. Enhances the order details with full product details from the products-service. """ try: customer_id = request.args['customer_id'] orders = self.orders_rpc.showCart(customer_id) except OrderNotFound as ex: self.logger.info(ex) return Response( json.dumps(RequestHandler.formatResponse(status_code=404, error='Missing', message=ex.message)), mimetype='application/json') except Exception as ex: self.logger.info(ex) return Response( json.dumps(RequestHandler.formatResponse(status_code=403, error='Exception', message=str(ex))), mimetype='application/json') return Response( json.dumps(RequestHandler.formatResponse(status_code=200, data=orders)), mimetype='application/json' )
def form_data_consumer(request): result_object = request.args['object'] if result_object == 'text': return Response(repr(request.form['text'])) f = request.files[result_object] return Response('\n'.join((repr(f.filename), repr(f.name), repr(f.content_type), f.stream.read())))
def decorated_auth(*args, **kwargs): if 'api-token' not in request.headers: return Response( mimetype="application/json", response=json.dumps({ 'error': 'Authentication token is not available, please login to get one' }), status=400) token = request.headers.get('api-token') data = Auth.decode_token(token) if data['error']: return Response(mimetype="application/json", response=json.dumps(data['error']), status=400) user_id = data['data']['user_id'] check_user = UserModel.get_one_user(user_id) if not check_user: return Response(mimetype="application/json", response=json.dumps({ 'error': 'user does not exist, invalid token' }), status=400) g.user = {'id': user_id} return func(*args, **kwargs)
def getProduct(self, request, product_id): """Gets product by `product_id` """ try: product = self.products_rpc.get(product_id) except ProductNotFound as ex: return Response( json.dumps(RequestHandler.formatResponse(status_code=404, error='Missing', message=ex.message)), mimetype='application/json') except Exception as ex: self.logger.info(ex) return Response( json.dumps(RequestHandler.formatResponse(status_code=403, error='Exception', message=str(ex))), mimetype='application/json') return Response( json.dumps(RequestHandler.formatResponse(status_code=200, data=product)), mimetype='application/json' )
def get_recommend_by_overview(self, request): """Test get Product from Service Product to Product Recommender""" try: header = dict() header["Access-Control-Allow-Origin"] = "*" title = request.args['title'] mode = request.args['mode'] k = int(request.args['k']) result = self.recommender_rpc.get_recommendations_by_item(title, mode, k) except ProductNotFound as ex: self.logger.info(ex) return Response( json.dumps(RequestHandler.formatResponse(status_code=404, error='Missing', message=ex.message)), mimetype='application/json', headers=header ) return Response( json.dumps(RequestHandler.formatResponse(status_code=200, data=result)), mimetype='application/json', headers=header )
def dispatch(self, environ, start_response): try: local.request = Request(environ) local.response = Response() local.session = Session(local.request.cookies.get("session")) try: local.url_adapter = url_adapter = url_map.bind_to_environ( environ) try: endpoint, params = url_adapter.match() except NotFound: endpoint = "notfound" params = {} local.endpoint = endpoint endpoints[endpoint](**params) except: if self.debug: raise responders.error() response = local.response local.session.save() local.session.set_cookie(local.response) except: if self.debug: raise response = Response("Fejlsidens fejlside.") return response(environ, start_response)
def getOrder(self, request, hashed_order_id): """Gets the order details for the order given by `order_id`. Enhances the order details with full product details from the products-service. """ try: order = self._getOrder(hashed_order_id) except OrderNotFound as ex: self.logger.info(ex) return Response( json.dumps(RequestHandler.formatResponse(status_code=404, error='Missing', message=ex.message)), mimetype='application/json') # TODO # except InvalidRequestError as ex: # return except Exception as ex: self.logger.info(ex) return Response( json.dumps(RequestHandler.formatResponse(status_code=403, error='Exception', message=str(ex))), mimetype='application/json') return Response( json.dumps(RequestHandler.formatResponse(status_code=200, data=order)), mimetype='application/json' )
def getSpecificProducts(self, request, product_ids): """Gets products by `product_id` list """ try: if '*' in product_ids: products = self.products_rpc.list() else: products = self.products_rpc.getSpecificList(product_ids) except ProductNotFound as ex: return Response( json.dumps(RequestHandler.formatResponse(status_code=404, error='Missing', message=ex.message)), mimetype='application/json') except Exception as ex: self.logger.info(ex) return Response( json.dumps(RequestHandler.formatResponse(status_code=403, error='Exception', message=str(ex))), mimetype='application/json') return Response( json.dumps(RequestHandler.formatResponse(status_code=200, data=products)), mimetype='application/json' )
def drip(request): """Drips data over a duration after an optional initial delay.""" args = CaseInsensitiveDict(request.args.items()) duration = float(args.get('duration', 2)) numbytes = min(int(args.get('numbytes', 10)), (10 * 1024 * 1024)) # set 10MB limit code = int(args.get('code', 200)) if numbytes <= 0: response = Response('number of bytes must be positive', status=400) return response delay = float(args.get('delay', 0)) if delay > 0: time.sleep(delay) pause = duration / numbytes def generate_bytes(): for i in xrange(numbytes): yield u"*".encode('utf-8') time.sleep(pause) response = Response(generate_bytes(), headers={ "Content-Type": "application/octet-stream", "Content-Length": str(numbytes) }) response.status_code = code return response
def view_status_code(request, codes): """Return status code or random status code if more than one are given""" if ',' not in codes: try: code = int(codes) except ValueError: return Response('Invalid status code', status=400) return status_code(code) choices = [] for choice in codes.split(','): if ':' not in choice: code = choice weight = 1 else: code, weight = choice.split(':') try: choices.append((int(code), float(weight))) except ValueError: return Response('Invalid status code', status=400) code = weighted_choice(choices) return status_code(code)
def app(request): if request.args.get('ping', 'N').upper() == 'Y': return Response("ok") if request.args.get('shutdown', 'N').upper() == 'Y': # func = request.environ.get('werkzeug.server.shutdown') # if func is None: # raise RuntimeError('Not running with the Werkzeug Server') # func() srv._BaseServer__shutdown_request = True return Response('Shutdown!') else: raise ex
def __call__(self, env, req, *args, **kwargs): res = super(JsonView, self).__call__(env, req, *args, **kwargs) if isinstance(res, Response): # rendering already done return res if res is None: # no content return Response(status=204) return Response(json.dumps(res), content_type='application/json')
def sensesJson(request): db_senses = get_database().senses if 'create' in request.args: wanted_lemma = request.args['create'] user = request.user if not user or user not in ADMINS: raise Forbidden('not an admin') info = list(db_senses.find({'lemma': request.args['create']})) if len(info) == 0: if gwn_dbname is not None: from gwn_db import germanet gwn = germanet.get_database(gwn_dbname) lemma_for_gwn = wanted_lemma.replace('#', '') synsets = gwn.synsets_for_word(lemma_for_gwn) else: synsets = [] objs = defaultdict(list) for synset in synsets: pos_cat = str(synset.word_category)[0].upper() lu_ids = [ lu.id for lu in synset.lexunit if lu.orth_form == lemma_for_gwn or lu.orth_var == lemma_for_gwn ] if lu_ids: lu_id = lu_ids[0] else: lu_id = '?' other_lus = [ lu.orth_form for lu in synset.lexunit if lu.orth_form != lemma_for_gwn and lu.orth_var != lemma_for_gwn ] if other_lus: lu_descr = '_'.join(other_lus) else: lu_descr = str(synset.word_class) objs[pos_cat].append([lu_id, lu_descr]) info = [] for k, v in objs.iteritems(): info.append(make_sense(wanted_lemma, k, v)) if len(info) == 0: if wanted_lemma[0].isupper(): info.append(make_sense(wanted_lemma, 'N')) else: info.append(make_sense(wanted_lemma, 'V')) info.append(make_sense(wanted_lemma, 'A')) info.append(make_sense(wanted_lemma, 'R')) return Response(json.dumps(info), mimetype="text/javascript") else: info = list(db_senses.find({})) return Response(json.dumps(info), mimetype="text/javascript")
def get_users(): try: data = list(db.user.find()) for u in data: u["_id"] = str(u["_id"]) return Response(response=json.dumps(data), status=200, mimetype="application/json") except Exception as ex: return Response(response=json.dumps({"message": "User not found"}), status=500, mimetype="application/json")
def openlayers(req, path='ol_merc.html'): global html if not html: try: f = open(path, 'rb') html = f.read() f.close() except IOError: return Response('Openlayers HTML/JS file not found: %s' % path, status=404, mimetype='text/html') return Response(html, status=200, mimetype='text/html')
def index(): """Upload a file, when the client has a valid session key. -- http://developer.getcloudapp.com/upload-file""" db, fs = current_app.db, current_app.fs config, sessions = current_app.config, current_app.sessions if request.method == 'POST' and not request.accept_mimetypes.accept_html: try: account = sessions.pop(request.form.get('key'))['account'] except KeyError: abort(401) acc = db.accounts.find_one({'email': account}) source = request.headers.get('User-Agent', 'Regenschirm++/1.0').split(' ', 1)[0] privacy = request.form.get('acl', acc['private_items']) _id = fs.upload_file(config, account, request.files.get('file'), source, privacy) items = acc['items'] items.append(_id) db.accounts.update({'_id': acc['_id']}, {'$set': { 'items': items }}, upsert=False) obj = fs.get(_id) if obj is None: abort(400) else: return jsonify(Item(obj, config, urlscheme(request))) else: users = db.accounts.find().count() files = fs.gfs._GridFS__files.count() size = sum([f['length'] for f in fs.gfs._GridFS__files.find()]) hits = sum([f['view_counter'] for f in fs.mdb.find()]) if request.args.get('format') == 'csv': fields = [('users', users), ('files', files), ('size', size), ('hits', hits)] return Response('\n'.join('%s,%s' % field for field in fields), 200) return Response(render_template("index.html", **locals()), 200, content_type="text/html")
def application(req): if req.method == 'POST': file_in = req.files['myfile'] buf = convert_doc(file_in) filename = file_in.filename.replace('.odt', '-converted.odt') filename = urllib.parse.quote(filename) resp = Response(buf.getvalue()) resp.content_type = 'application/x-download' resp.headers.add('Content-Disposition', 'attachment', filename=filename) return resp return Response(HTML, content_type='text/html')
def rtf(self, case_id, task_id): task = self._validate_task(case_id, task_id) if task is not None: self.check_permissions(self.current_user, task, 'view') stringio = render_rtf(task.notes) if stringio is None: return Response(self.error_msg, mimetype='text/html', status=200) return Response(stringio.getvalue(), direct_passthrough=True, mimetype='application/rtf', status=200) else: return self.return_404()
def delete_User(id): try: val = db.user.delete_one({"_id": ObjectId(id)}) return Response(response=json.dumps({ "message": "user deleted", "id": f"{id}" }), status=200, mimetype="application/json") except Exception as ex: return Response(response=json.dumps({"message": "User can not delete"}), status=500, mimetype="application/json")
def sharedir_download(dname, rpath): rootpath = os.path.abspath(settings.SHAREDIR.directories.get(dname)) if not rootpath: raise NotFound apath = os.path.abspath(os.path.join(rootpath, rpath)) if (not apath.startswith(rootpath)) or (not os.path.isfile(apath)): raise NotFound def _opener(filename): return (open(filename, 'rb'), datetime.utcfromtimestamp(os.path.getmtime(filename)), int(os.path.getsize(filename))) guessed_type = mimetypes.guess_type(apath) mime_type = guessed_type[0] or 'application/octet-stream' headers = [] headers.append(('Content-Type', mime_type)) if request.range: range = request.range else: range = parse_range_header(request.environ.get('HTTP_RANGE')) #when request range,only recognize "bytes" as range units if range and range.units == "bytes": rbegin, rend = range.ranges[0] try: fsize = os.path.getsize(apath) except OSError as e: return Response("Not found", status=404) if (rbegin + 1) < fsize: if rend == None: rend = fsize - 1 headers.append(('Content-Length', str(rend - rbegin + 1))) headers.append( ('Content-Range', '%s %d-%d/%d' % (range.units, rbegin, rend, fsize))) return Response(FileIterator(apath, rbegin, rend), status=206, headers=headers, direct_passthrough=True) f, mtime, file_size = _opener(apath) return Response(wrap_file(request.environ, f), status=200, headers=headers, direct_passthrough=True)
def generic_template_renderer(self, request): path = '%s/templates/%s.html' % (os.path.dirname(__file__), request.environ['endpoint']) try: source = open(path).read() except IOError: raise NotFound() template = Template(source) files = [] for name, file in request.files.items(): # Save the uploaded files to tmp storage. # The calling test should delete the files. fh, fname = tempfile.mkstemp() os.close(fh) file.save(fname) files.append((name, (file.filename, file.content_type, file.content_length, fname))) context = dict( request=request, request_id=self.call_count, args=dumps(sorted(request.args.items(multi=True))), form=dumps(sorted(request.form.items(multi=True))), data=dumps( sorted( request.args.items(multi=True) + request.form.items(multi=True))), files=dumps(sorted(files)), referrer=request.referrer or '', #args=.. ) body = template.render(context) return Response(body, mimetype='text/html')
def fake_ods_application(request): primary_role = request.args.get("PrimaryRoleId") target_org_id = request.args.get("TargetOrgId") return Response( _get_fake_response(primary_role, target_org_id), mimetype="application/json", )
def handle_traceback(exc): out = cStringIO.StringIO() print_exc(file=out) formatted_environ = pformat(request.environ) response = Response('%s\n%s\n' % (out.getvalue(), formatted_environ), status=500) return response
class JSONRequestHandler(object): def __init__(self): self.funcs = {} def register_function(self, func, name=None): self.funcs[name or func.__name__] = func def handle_request(self): try: method_name = local.request.args['method'] if not local.request.data: args = () kwargs = {} else: args = loads(local.request.data) if isinstance(args, dict): kwargs = dict( (str(key), value) for key, value in args.items()) args = () elif isinstance(args, list): kwargs = {} else: raise TypeError('arguments as object or list expected') #XXX:dc: use flatland to validate these args before passing onward response = { 'data': self.funcs[method_name](*args, **kwargs), 'error': None } except Exception, e: response = {'data': None, 'error': str(e).decode('utf-8')} body = dumps(response, indent=local.request.is_xhr and 2 or 0) return Response(body + '\n', mimetype='application/json')
def upload_file(): if request.method == 'POST': f = request.files['file'] # create a secure filename filename = secure_filename(f.filename) # save file to /static/uploads filepath = os.path.join(app.config['UPLOAD_FOLDER'],filename) f.save(filepath) # load the example image and convert it to grayscale image = cv2.imread(filepath) gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) # apply thresholding to preprocess the image gray = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU)[1] # apply median blurring to remove any blurring gray = cv2.medianBlur(gray, 3) # save the processed image in the /static/uploads directory ofilename = os.path.join(app.config['UPLOAD_FOLDER'],"{}.png".format(os.getpid())) cv2.imwrite(ofilename, gray) # perform OCR on the processed image text = pytesseract.image_to_string(Image.open(ofilename)) # remove the processed image os.remove(ofilename) return Response(render_template("apioutput.json", outputtext=json.dumps(text), fname=filename), mimetype="application/json")
def ajax_object_track(req): object_name = req.values.get('obj') latitude = req.values.get('latitude', type=float) longitude = req.values.get('longitude', type=float) obscode = req.values.get('obscode') altitude = req.values.get('altitude') # todo add configuration to dry up defaults cmap_name = req.values.get('cmap_name') sigma_high = req.values.get('sigma_high', type=int) sigma_low = req.values.get('sigma_low', type=int) ephemerides_req = EphemeridesRequest(longitude, latitude, altitude=altitude, obscode=obscode) ephemerides_set = ephemerides_req.make_request() ephemerides = ephemerides_set.get(object_name) atg = AtlasTrackGraphic(ephemerides) encoded_graphic = to_data_uri(atg.render(cmap_name, sigma_low, sigma_high), 'image/png') ephemeride_table = render("html/ephemeride_table.html", dict(ephemerides=ephemerides)) return Response(dumps( dict(graphic=encoded_graphic, ephemeride_table=ephemeride_table)), mimetype='application/json')
def object_list(req): latitude = req.values.get('latitude', type=float) longitude = req.values.get('longitude', type=float) altitude = req.values.get('altitude', type=float) obscode = req.values.get('obscode') er = EphemeridesRequest(latitude, longitude, altitude=altitude, obscode=obscode) ephemerides_set = er.make_request() all_available_neos = get_neos() viewable_neos = set(ephemerides_set.list_objects()) data = [] for available_neo in all_available_neos: if available_neo.temporary_designation in viewable_neos: data.append(available_neo.row()) table_data = { 'data': data, 'columns': [{ 'data': name } for name in NEOCPEntry._table] } return Response(dumps(table_data), mimetype='application/json')