def upload_file(request: http.Request, request_data: http.RequestData) -> http.Response: if request.method == 'POST': file = request_data.get('file1') filename = file.filename print(filename) fileDes = '/var/www/html/wp-content/file/' + filename if os.path.isdir(fileDes): if os.path.isfile(str(fileDes) + '/' + filename): content = filename + ' already exists. Change your file.name' headers = {'Content-Type': 'text/plain'} return http.Response(content, headers=headers) else: filename = secure_filename(file.filename) file.save(os.path.join(fileDes, filename)) content = 'Success file upload' headers = {'Content-Type': 'text/plain'} return http.Response(content, headers=headers) else: os.makedirs(str(fileDes)) filename = secure_filename(file.filename) file.save(os.path.join(fileDes, filename)) content = 'Make your new Directory and Success file upload' headers = {'Content-Type': 'text/plain'} return http.Response(content, headers=headers)
def exception_handler(environ: wsgi.WSGIEnviron, exc: Exception) -> http.Response: if isinstance(exc, exceptions.APIException): return http.Response({'message': exc.message}, exc.status_code) if is_running_from_reloader() or environ.get('APISTAR_RAISE_500_EXC'): raise message = traceback.format_exc() return http.Response(message, 500, {'Content-Type': 'text/plain; charset=utf-8'})
def exception_handler(self, exc: Exception) -> http.Response: if isinstance(exc, exceptions.Found): return http.Response('', exc.status_code, {'Location': exc.location}) if isinstance(exc, exceptions.HTTPException): if isinstance(exc.detail, str): content = {'message': exc.detail} else: content = exc.detail return http.Response(content, exc.status_code, {}) raise
def serve_schema_js(schema: APISchema, templates: Templates) -> http.Response: codec = CoreJSONCodec() base64_schema = base64.b64encode(codec.encode(schema)).decode('latin1') template = templates.get_template('apistar/schema.js') content = template.render(base64_schema=base64_schema) headers = {'Content-Type': 'application/javascript'} return http.Response(content, headers=headers)
def finalize_response(self, ret: ReturnValue) -> http.Response: if isinstance(ret, http.Response): data, status, headers, content_type = ret if content_type is not None: return ret else: data, status, headers, content_type = ret, 200, {}, None if data is None: content = b'' content_type = 'text/plain' elif isinstance(data, str): content = data.encode('utf-8') content_type = 'text/html; charset=utf-8' elif isinstance(data, bytes): content = data content_type = 'text/html; charset=utf-8' else: content = json.dumps(data).encode('utf-8') content_type = 'application/json' if not content and status == 200: status = 204 content_type = 'text/plain' return http.Response(content, status, headers, content_type)
def exception_handler(environ: wsgi.WSGIEnviron, exc: Exception) -> http.Response: if isinstance(exc, exceptions.Found): return http.Response('', exc.status_code, {'Location': exc.location}) if isinstance(exc, exceptions.APIException): if isinstance(exc.detail, str): content = {'message': exc.detail} else: content = exc.detail return http.Response(content, exc.status_code) if is_running_from_reloader() or environ.get('APISTAR_RAISE_500_EXC'): raise message = traceback.format_exc() return http.Response(message, 500, {'Content-Type': 'text/plain; charset=utf-8'})
def get_request(request: http.Request) -> http.Response: return http.Response({ 'method': request.method, 'url': request.url, 'headers': dict(request.headers), 'body': request.body.decode('utf-8') })
async def create_project(data: Project._scheme, auth: Auth, session: Session): data.pop('id') obj = Project(**data) obj.user_id = auth.get_user_id() session.add(obj) session.commit() return http.Response(obj.render(), status=201)
def exception_handler(self, exc: Exception) -> http.Response: if isinstance(exc, HTTPException): return http.Response(exc.detail, status=exc.status_code, headers=exc.headers) else: return super().exception_handler(exc)
def render_response(handler: Handler, injector: Injector, settings: Settings, accept: http.Header, ret: ReturnValue) -> http.Response: """ Render a response, using content negotiation to determine an appropriate renderer. Used in the default `BEFORE_REQUEST` configuration. """ if isinstance(ret, http.Response): data, status, headers, content_type = ret if content_type is not None or (status >= 300 and status <= 399): return ret else: data, status, headers, content_type = ret, 200, {}, None if data is None or data == b'': content = b'' content_type = None else: default_renderers = settings.get('RENDERERS', DEFAULT_RENDERERS) renderers = getattr(handler, 'renderers', default_renderers) renderer = negotiate_renderer(accept, renderers) if renderer is None: raise exceptions.NotAcceptable() content = injector.run(renderer.render, {'response_data': data}) if isinstance(content, http.Response): return content content_type = renderer.get_content_type() if not content and status == 200: status = 204 content_type = None return http.Response(content, status, headers, content_type)
def criar_produto(produto: schemas.Produto, session: Session): if not produto: return db_produto = session.Produto(**produto) db_produto.save() return http.Response(content=schemas.Produto(db_produto.__dict__), status=201)
async def delete_article(article_id: int, password: http.Header): # if not is_auth(password): # raise exceptions.BadRequest() try: repo.delete_article(article_id) except LookupError: raise exceptions.NotFound() return http.Response('', status_code=204)
def download_response(): return http.Response(b'...', headers={ 'Content-Type': 'image/jpeg', 'Content-Disposition': 'attachment; filename=example.jpg;' })
def download_response(): return http.Response( b"...", headers={ "Content-Type": "image/jpeg", "Content-Disposition": "attachment; filename=example.jpg;", }, )
def run(request: http.Request, words, scale=1, level='L'): try: qr = myqr.run(words, scale=int(scale), version=1, level=level) imgByteArr = io.BytesIO() qr.save(imgByteArr, format='PNG') return http.Response(imgByteArr.getvalue(), headers={'Content-Type': 'image/png'}) except Exception as e: return http.JSONResponse({'message': e.args}, status_code=400)
def token_login(user: schemas.TokenUser): from django_apistar.authentication.models import Token if not user: return http.Response({"message": "Invalid credentials."}, status=400) user = authenticate(username=user['username'], password=user['password']) if user: try: return user.auth_token.key except ObjectDoesNotExist: token = Token(user=user) token.save() return user.auth_token.key else: return http.Response({"message": "Invalid credentials."}, status=400)
def exception_handler(self, exc: Exception) -> http.Response: if isinstance(exc, exceptions.Found): return http.Response( status=exc.status_code, headers={'Location': exc.location} ) if isinstance(exc, exceptions.HTTPException): if isinstance(exc.detail, str): content = {'message': exc.detail} else: content = exc.detail return http.Response(content, exc.status_code, {}) logging.exception(exc) return http.Response( {'message': 'Unexpected error'}, status=500 )
def calendar_notification(request: http.Request) -> dict: print({ 'method': request.method, 'url': request.url, 'headers': dict(request.headers), 'body': request.body.decode('utf-8') }) pp(dict(request.headers)) return http.Response()
def post(slug: str): try: db_post = models.BlogPost.objects.get(slug=slug) except models.BlogPost.DoesNotExist: return http.Response( {'message': 'Post {} does not exist.'.format(slug)}, status=404) post = schemas.BlogPost(db_post.__dict__) post['body'] = markdownify(post['body']) return post
def test_nested_transaction_on_error(session): hook = SQLAlchemyTransactionHook(nested=True) resp = http.Response(content='test') txn = session.begin_nested() hook.on_request(session) puppy = PuppyModel() session.add(puppy) hook.on_error(resp) txn.rollback()
async def auth_token(headers: http.Headers, body: http.Body, settings: Settings): """ Simple proxy to Gluu. Example: http -f -a user:secret post /auth/token grant_type=client_credentials scope=uapi_persons_get """ async with aiohttp.ClientSession() as session: endpoint = urllib.parse.urljoin(settings['QVARN']['TOKEN_ISSUER'], 'oxauth/.well-known/openid-configuration') async with session.get(endpoint) as resp: config = await resp.json() headers = { 'authorization': headers['authorization'], 'content-type': headers['content-type'], } async with session.post(config['token_endpoint'], data=body, headers=headers) as resp: content_type = resp.headers['content-type'] if content_type == 'application/json': return http.Response(await resp.json(), status=resp.status) else: return http.Response(await resp.read(), status=resp.status, content_type=content_type)
def download(): fig = plt.figure(1) ax = fig.add_subplot(111) t = np.arange(0.0, 3.0, 0.01) s = np.sin(2 * np.pi * t) ax.plot(t, s) buf = BytesIO() fig.canvas.print_figure(buf, format='svg') headers = { 'Content-Type': 'image/svg+xml', 'Content-Disposition': 'attachment; filename="graph.svg"', } return http.Response(buf.getvalue(), headers=headers)
async def func(session: Session, filters: bind(Filters, model), ordering: bind(Ordering, model), limit: int, offset: int, query_params: http.QueryParams): qs = session.query(model) if filters: qs = qs.filter(or_(*filters)) if ordering: qs = qs.order_by(ordering()) count = qs.count() if limit: qs = qs.limit(limit) if offset: qs = qs.offset(offset) return http.Response([obj.render() for obj in qs], headers={"X-Total-Count": str(count)})
def fetch_auth_code(code: str = None, state: str = None) -> Union[str, http.Response]: if not code: return "no is no\nbut it's fine, i understand\nmaybe next time (:" telegram_id = check_state(state) if not telegram_id: return http.Response( "wow, this is very bad state in ur url. don't do that again", status_code=400) url = api_url('oauth/token') res = requests.post(url, json=params_for_token(code=code)) data = res.json() save_credentials(telegram_id, data) bot = Bot(TELEGRAM_BOT_TOKEN) bot.send_message(telegram_id, 'subscribed to trakt') return 'everything is fine, my dude, u may close this tab now and jump back to the bot'
def token_logout(authorization: http.Header): from django_apistar.authentication.models import Token if not authorization: return None scheme, token = authorization.split() if scheme.lower() != 'bearer': return None try: user = Token.objects.get(key=token).user except Token.DoesNotExist: return None if user: user.auth_token.delete() return http.Response({"message": "Logged out."}, status=200)
def stream_csv(headers, rows): """ Create CSV as StringIO and stream it as a file to be downloaded """ output = io.StringIO() writer = csv.writer(output, delimiter=',') writer.writerow(headers) writer.writerows(rows) content = output.getvalue() headers = { 'Content-Type': 'text/csv; charset=utf-8', 'Content-Disposition': 'attachment; filename="transcriptions.csv"', } return http.Response(content=content.encode('utf-8'), headers=headers, content_type='text/csv')
def get_response(self, method: http.Method, headers: http.Headers, file_wrapper: FileWrapper) -> http.Response: wsgi_style_headers = { 'HTTP_' + k.upper().replace('-', '_'): v for k, v in headers.items() } response = self._file.get_response(method, wsgi_style_headers) if response.file is not None: content = file_wrapper(response.file) else: # We hit this branch for HEAD requests content = b'' response_headers = dict(response.headers) content_type = response_headers.pop('Content-Type', None) return http.Response(content, status=response.status, headers=response_headers, content_type=content_type)
def download(): import squarify values = sorted([i**3 for i in range(1, 50)], reverse=True) cmap = mlp.cm.Spectral norm = mlp.colors.Normalize(vmin=min(values), vmax=max(values)) colors = [cmap(norm(value)) for value in values] fig = plt.figure(1) ax = fig.add_subplot(111) squarify.plot(sizes=values, alpha=.8, color=colors, ax=ax) ax.axis("off") buf = BytesIO() fig.canvas.print_figure(buf, format='svg') headers = { 'Content-Type': 'image/svg+xml', 'Content-Disposition': 'attachment; filename="graph.svg"', } return http.Response(buf.getvalue(), headers=headers)
def download(): # Load the example tips dataset iris = sns.load_dataset("iris") # Plot tip as a function of toal bill across days g = sns.lmplot(x="sepal_length", y="sepal_width", hue="species", truncate=True, size=5, data=iris) # Use more informative axis labels than are provided by default g.set_axis_labels("Sepal length (mm)", "Sepal width (mm)") fig = g.fig buf = BytesIO() fig.canvas.print_figure(buf, format='svg') headers = { 'Content-Type': 'image/svg+xml', 'Content-Disposition': 'attachment; filename="graph.svg"', } return http.Response(buf.getvalue(), headers=headers)
def serve_schema(app: App): codec = OpenAPICodec() content = codec.encode(app.document) headers = {'Content-Type': 'application/vnd.oai.openapi'} return http.Response(content, headers=headers)