I'm running a Bokeh app as shown in standalone_embed.py and want to use an authentication hook with it, as shown here. How do I set the auth_module in bokeh.settings.settings in standalone_embed.py?
I tried
from bokeh.settings import settings
settings.auth_module = "auth.py"
settings.xsrf_cookies = True
but that doesn't seem to do anything. Any help appreciated, thanks!
Found the answer:
Server can take the authentication module as param as follows:
auth_module_path = <path to auth.py>
if auth_module_path:
server_kwargs['auth_provider'] = AuthModule(auth_module_path)
server = Server(
bokeh_applications, # list of Bokeh applications
io_loop=loop, # Tornado IOLoop
**server_kwargs # port, num_procs, etc.
)
Related
i am new in airflow and gRPC
i use airflow running in docker with default setting
https://airflow.apache.org/docs/apache-airflow/stable/start/docker.html
when i try to do in this link
https://airflow.apache.org/docs/apache-airflow-providers-grpc/stable/_api/airflow/providers/grpc/index.html
channel = grpc.insecure_channel('localhost:50051')
number = calculator_pb2.Number(value=25)
con = GrpcHook(grpc_conn_id='grpc_con',
interceptors=[UnaryUnaryClientInterceptor]
)
run = GrpcOperator(task_id='square_root',
stub_class=calculator_pb2_grpc.CalculatorStub(channel),
call_func='SquareRoot',
grpc_conn_id='grpc_con',
data=number,
log_response=True,
interceptors=[UnaryUnaryClientInterceptor]
)
no response in DAG log even server is shut down or server port is wrong, but it works if i call with simple client
What you're looking for I guess is the GrpcOperator example.
In your example, the wrong parameter is data.
The data parameter should be data={'request':calculator_pb2.Number(value=25)}, if you don't modify generated protof files.
This is an example.
from airflow.providers.grpc.operators.grpc import GrpcOperator
from some_pb2_grpc import SomeStub
from some_pb2 import SomeRequest
GrpcOperator(task_id="task_id", stub_class=SomeStub, call_func='Function', data={'request': SomeRequest(var='data')})
I just came across rollbar and wanted to include it in my Python project.
This is the standard way in which I am told to implement rollbar from the website.
import rollbar
rollbar.init('KEY')
try:
a = s
except:
rollbar.report_exc_info()
Is there a better way to implement this without going through all my try except blocks and replacing them with rollbar.report_exc_info()
Can there be a decorator implementation for this?
My current project is a Flask app that provides API's to end users.
Here's an example for rollbar integration in Flask apps.
https://github.com/rollbar/rollbar-flask-example/blob/master/hello.py
#app.before_first_request
def init_rollbar():
"""init rollbar module"""
rollbar.init(
# access token for the demo app: https://rollbar.com/demo
'fc316ac1f7404dc28af26d5baed1416c',
# environment name
'flasktest',
# server root directory, makes tracebacks prettier
root=os.path.dirname(os.path.realpath(__file__)),
# flask already sets up logging
allow_logging_basic_config=False)
# send exceptions from `app` to rollbar, using flask's signal system.
got_request_exception.connect(rollbar.contrib.flask.report_exception, app)
I' trying to combine two independent Flask apps like the example below:
from geventwebsocket import WebSocketServer, Resource
...
server = WebSocketServer(('', 8080), Resource({
'/': frontend,
'/one': flask_app_one,
'/two': flask_app_two}))
server.serve_forever()
Inside each Flask app I declare the full path, isn't that suppose to be relative path, inside flask_app_one:
from flask import Flask
app = Flask(__name__)
#app.route('/one/ping')
def ping():
return 'hello\n'
Why I should specify in #app.route('/one/ping') instead of just #app.route('/ping') since all traffic to /one will be forwarded to the corresponding app?
Let me know if you need any additional info I kept my example clean
Thank you
Finally I have managed to do it with the so called Application Dispatching and the resources found in this page:
http://flask.pocoo.org/docs/0.10/patterns/appdispatch/#app-dispatch
Thanks
I'm trying to use a javascript plotting library to plot data I calculated in the python console (IPython) using Numpy.
I was thinking of a design to accomplish this. I thought it should look something like this:
This means I'm using a Flask app to sent a server-side event to the client as soon as the data is ready in the IPython process.
1) Is this the right approach?
2) How can I send data from the console to my Flask app? I think I need to run the Flask App with gevent so I can listen to commands from the other python process?
3) How can I send the data using a server-side event to the client? I found some examples of server-side events but I don't see how they can sent arbitrary data. Example:
import gevent
import gevent.monkey
from gevent.pywsgi import WSGIServer
gevent.monkey.patch_all()
from flask import Flask, request, Response, render_template
app = Flask(__name__)
def event_stream():
count = 0
while True:
gevent.sleep(2)
yield 'data: %s\n\n' % count
count += 1
#app.route('/my_event_source')
def sse_request():
return Response(
event_stream(),
mimetype='text/event-stream')
#app.route('/')
def page():
return render_template('sse.html')
if __name__ == '__main__':
http_server = WSGIServer(('127.0.0.1', 8001), app)
http_server.serve_forever()
This example uses a predefined event_stream() function. I am looking for a way to send the data from the python console with a server-side event to the client.
Maybe there is another and better approach?
Is it $ipython console(zmq console) of the plain IPython terminal ($ipython) ?
Why not directly use the IPython Notebook ?
(Notebook, QT and zmq console can allow a 3rd program to listen for event published by the kernel).
Have a look at IPEP 21 and current implementation proposal which is bidirectional kernel<-> js communication.
Did you had a look at bokeh from continuum that seem to do almost what you want ?
(also IPython not iPython in the images, but this is a detail)
When I attempt to redirect incoming traffic to https I get an infinite redirect loop.
#app.route('/checkout/')
def checkout():
checkout = "https://myapp.herokuapp.com/checkout/"
if checkout != request.url:
print checkout, request.url
return redirect(checkout)
return render_template('checkout.html', key=keys['publishable_key'])
The request.url is never changed to prefix https. I want to use heroku's piggyback ssl to minimize cost.
1) Do "pip install flask-sslify"
(github is here: https://github.com/kennethreitz/flask-sslify)
2) Include the following lines:
from flask_sslify import SSLify
if 'DYNO' in os.environ: # only trigger SSLify if the app is running on Heroku
sslify = SSLify(app)
On Heroku, SSL (https) is terminated before it reaches your application, so you app never actually sees SSL traffic. To check whether a request was made with https, you instead have to inspect the x-forwarded-proto header. More info here: How to make python on Heroku https only?
UPDATE: For your use, you should just check request.url for "myapp.herokuapp.com/checkout/"; and verify that the header is "https"
I tried SSLify, url_for _scheme, and setting a PREFERRED_URL_SCHEME; however none worked out, at the release level at least.. (worked fine locally) Then I thought;
#app.before_request
def beforeRequest():
if not request.url.startswith('https'):
return redirect(request.url.replace('http', 'https', 1))
This is essentially another way to get it done without any configurations, or extensions.
I was able to repurpose the flask-sslify code for a single view. Just needed to check whether or not the request was being made with SSL and add proper headers to the response. https://github.com/kennethreitz/flask-sslify
#app.route('/checkout/')
def checkout():
checkout = "https://myapp.herokuapp.com/checkout/"
if request.headers.get('X-Forwarded-Proto', 'http') == 'https':
resp = make_response(render_template('checkout.html', key=keys['publishable_key']))
return set_hsts_header(resp)
return redirect(checkout, code=302)
def set_hsts_header(response):
"""Adds HSTS header to each response."""
response.headers.setdefault('Strict-Transport-Security', hsts_header)
return response
def hsts_header():
"""Returns the proper HSTS policy."""
hsts_policy = 'max-age={0}'.format(31536000) #year in seconds
if self.hsts_include_subdomains:
hsts_policy += '; includeSubDomains'
return hsts_policy
You just need to check the X-Forwarded-Proto header. If its false, redirect to the equivalent https url.
Here the code to enforce https for all calls on a flask app running on heroku:
#app.before_request
def enforceHttpsInHeroku():
if request.headers.get('X-Forwarded-Proto') == 'http':
url = request.url.replace('http://', 'https://', 1)
code = 301
return redirect(url, code=code)
You can do something like this:
#app.before_request
def before_request():
if 'DYNO' in os.environ: # Only runs when on heroku
if request.url.startswith('http://'):
url = request.url.replace('http://', 'https://', 1)
code = 301
return redirect(url, code=code)
On my answer to another question I have stated the upto date Flask recommendations. Use Talisman instead of SSLify.
For Flask use Talisman. Flask, Heroku and SSLify
documentations favor the use of Talisman over SSLify because the
later is no longer maintained.
From SSLify:
The extension is no longer maintained, prefer using Flask-Talisman as
it is encouraged by the Flask Security Guide.
Install via pip:
$ pip install flask-talisman
Instatiate the extension (example):
from flask import Flask
from flask_talisman import Talisman
app = Flask(__name__)
if 'DYNO' in os.environ:
Talisman(app)
Talisman enables CSP (Content Security Policy) by default only
allowing resources from the same domain to be loaded. If you want to
disable it and deal with the implications:
Talisman(app, content_security_policy=None)
If you don't want to disable it you have set the
content_security_policy argument to allow resources from external
domains, like CDNs, for instance. For that refer to the
documentation.