I'm setting up my Braintree web-hooks in Django, as Braintree docs says i have to add this method
from flask import Flask, request, render_template, Response
...
def webhook():
webhook_notification = gateway.webhook_notification.parse(str(request.form['bt_signature']), request.form['bt_payload'])
# Example values for webhook notification properties
print(webhook_notification.kind)
print(webhook_notification.timestamp)
return Response(status=200)
everything is ok except i have no idea what gateway is, and I'm getting undefined name error
my Django code
#csrf_exempt
def webhook(request):
print("post:: ", request.POST)
webhook_notification = gateway.webhook_notification.parse(str(request.form["bt_signature"]), request.form["bt_payload"])
print(webhook_notification.kind)
print(webhook_notification.timestamp)
return HttpResponse("Ok")
sorry if missed up things, I haven't try flask yet.
That's not related to Flask nor Django.
It's the gateway object you configure for any use of the Braintree Python SDK, รก la
import braintree
gateway = braintree.BraintreeGateway(
braintree.Configuration(
braintree.Environment.Sandbox,
merchant_id="use_your_merchant_id",
public_key="use_your_public_key",
private_key="use_your_private_key",
)
)
Related
I am trying to integrate Coinbase Commerce Webhook API in my Django App; but it seems am doing things in the right way. I have searched the web for more than 2 days but no solution available for this. Coinbase commerce official documentation did not provide way to integrate this in Django. Please your help will be appreciated. This is what I have tried; but keep on throwing an error.
from django.conf import settings
from django.views.decorators.csrf import csrf_exempt
from coinbase_commerce.error import WebhookInvalidPayload, SignatureVerificationError
from coinbase_commerce.webhook import Webhook
from django.http import HttpResponse
import json
WEBHOOK_SECRET = settings.COINBASE_SECRET
#csrf_exempt
def payment_webhook(request):
request_data = request.data.decode('utf-8')
request_sig = request.headers.get('X-CC-Webhook-Signature', None)
try:
event = Webhook.construct_event(request_data, request_sig, WEBHOOK_SECRET)
except (WebhookInvalidPayload, SignatureVerificationError) as e:
return HttpResponse(e, status=400)
print("Received event: id={id}, type={type}".format(id=event.id, type=event.type))
return HttpResponse('ok', status=200)
I face the same issue, but since I'm only creating an endpoint to receive the webhook from 'charge:confirmed' which confirms that someone payed. I decided to do the validation of a request differently.
Upon receiving a request from the webhook, I check in the event['data']['timeline'] object if the status COMPLETED is present which according to: https://commerce.coinbase.com/docs/api/ specifies that the payment has been completed.
In Django, you have to use request.body.decode('utf-8') instead of request.data.decode('utf-8')
request_data = request.body.decode('utf-8')
Sorry, new to Flask-Dance.
I'm using the template code from:
https://github.com/singingwolfboy/flask-dance-google/blob/master/google.py
import os
from flask import Flask, redirect, url_for
from flask_dance.contrib.google import make_google_blueprint, google
app = Flask(__name__)
app.secret_key = os.environ.get("FLASK_SECRET_KEY", "supersekrit")
app.config["GOOGLE_OAUTH_CLIENT_ID"] = os.environ.get("GOOGLE_OAUTH_CLIENT_ID")
app.config["GOOGLE_OAUTH_CLIENT_SECRET"] = os.environ.get("GOOGLE_OAUTH_CLIENT_SECRET")
google_bp = make_google_blueprint(scope=["profile", "email"])
app.register_blueprint(google_bp, url_prefix="/login")
#app.route("/")
def index():
if not google.authorized:
return redirect(url_for("google.login"))
resp = google.get("/oauth2/v1/userinfo")
assert resp.ok, resp.text
return "You are {email} on Google".format(email=resp.json()["email"])
As I understand , if google.authorized is NOT true, it redirects to the route "google.login".
I'm wondering is there a way to know if I have been redirected as a result of being unauthorized from O-auth vs just being directed to the login url.
Thanks
Since you are new to Flask-Dance, I would like to recommend my library Authlib instead. You can check the Google login example for Flask at:
https://github.com/authlib/demo-oauth-client/tree/master/flask-google-login
I have a Flask app which has a Flask-RestPlus API as well as a "/" route. When I try to access "/" however, I get a 404. If I remove the Flask-RestPlus extension, the route works. How do I make both parts work together?
from flask import Flask
from flask_restplus import Api
app = Flask(__name__)
api = Api(app, doc="/doc/") # Removing this makes / work
#app.route("/")
def index():
return "foobar"
This is an open issue in Flask-RestPlus. As described in this comment on that issue, changing the order of the route and Api solves the issue.
from flask import Flask
from flask_restplus import Api
app = Flask(__name__)
#app.route("/")
def index():
return "foobar"
api = Api(app, doc="/doc/")
flask-restplus defines a different way of assigning routes according to their docs:
#api.route('/')
class Home(Resource):
def get(self):
return {'hello': 'world'}
Notice that the api variable is used instead of the app. Moreover, a class is used although I am not 100% sure it is required.
I have a Javascript application and a Flask application. When the user send data from Js to Flask, I store it on session and it works fine at a specific route:
#app.route(...)
def user(...):
session['name'] = name
print(session['name']) # Works !
But when I tr to get the values on session from another method / route the session is empty:
#app.route(...)
def current():
print(session.keys(), session.values) # Empty !
I have installed Flask Session and set the config to:
'SECRET_KEY': b'...',
'SESSION_TYPE': 'filesystem', # Memcache, null and redis
'SESSION_PERMANENT': False, # True
And then started the Flask application and it not work. I have also try to set session.modified = True after I add some new value to session and still not work.
I have read lots of threads on Stack Over Flow, Reddit, etc; and nothing worked. Tips please ?
TL;DR, enable CORS and credentials support on the back end, and use credentials in the front end code when issuing requests.
I recently ran into a similar issue where I was developing a front end and a back end in separate apps. I noticed that each time I issued a request from the front end client, it would create a new session for each request, which would rapidly bloat the session storage on the back end and made user tracking difficult if not impossible.
I'm assuming that you're Javascript app and Flask app are running separately (i.e., the javascript is not on a template being served by the Flask app and hence the js requests are coming from a different origin).
Suppose we have a simple app with Flask-Session enabled running on port 5000:
from flask import Flask, session
from flask_session import Session
app = Flask(__name__)
SECRET_KEY = "changeme"
SESSION_TYPE = 'filesystem'
app.config.from_object(__name__)
Session(app)
#app.route('/foo')
def foo():
return session.sid
#app.route('/bar')
def bar():
return session.sid
Now if we run the app if we navigate to either route on a browser(e.g., http://localhost:5000/foo), we would get the same session id. If you open another tab, open the developer tools and issue the following command in the console, you'd get a cors error:
// Using fetch, you can use jquery or axios
fetch("http://localhost:5000/foo").then(response => {
return response.text()
}).then(data => {
console.log(data)
})
You can fix this easily by installing Flask-CORS and wrapping your app in the CORS class:
from flask import Flask, session
from flask_session import Session
from flask_cors import CORS
app = Flask(__name__)
SECRET_KEY = "changeme"
SESSION_TYPE = 'filesystem'
app.config.from_object(__name__)
Session(app)
CORS(app)
#app.route('/foo')
def foo():
return session.sid
#app.route('/bar')
def bar():
return session.sid
Now if you run the javascript fetch function above, it prints out a different session id each time the request is invoked, even for the same route. That's because Flask can't track the session unless you're issuing the requests from the same origin or unless you provide some way for flask to identify the session. You can do this from your JS by allowing credentials to be passed:
fetch("http://localhost:5000/foo",
{ credentials: 'include' }).then(response => {
return response.text()
}).then(data => {
console.log(data)
})
However, you will get another CORS error regarding Access-Control-Allow-Credentials. You can fix this in you're Flask app by import the cross_origin decorator, wrapping your routes in the decorator and passing supports_credentials=True to the decorator. The flask code would look something like this:
from flask import Flask, session
from flask_session import Session
from flask_cors import CORS, cross_origin
app = Flask(__name__)
SECRET_KEY = "changeme"
SESSION_TYPE = 'filesystem'
app.config.from_object(__name__)
Session(app)
CORS(app)
#app.route('/foo')
#cross_origin(supports_credentials=True)
def foo():
return session.sid
#app.route('/bar')
#cross_origin(supports_credentials=True)
def bar():
return session.sid
Now flask can track the session by the requester (in this case, the browser running the Javascript app).
I had the same problem using classic post request in html. The session, which was still storing values in previous route, would empty itself after my post request.
I solved this using:
app.config.update(SESSION_COOKIE_SAMESITE="None", SESSION_COOKIE_SECURE=True)
I am sharing this in case others are facing the same issue.
Trying to enable login in flask with flask-security. The following code works fine (I import in __init__.py)
from flask import Blueprint, render_template, request, redirect, url_for
from coursly import app
from coursly.models import *
from flask.ext.security import Security, LoginForm, SQLAlchemyUserDatastore
user_datastore = SQLAlchemyUserDatastore(db, user.User, user.Role)
Security(app, user_datastore)
user = Blueprint('user', __name__)
#user.route('/')
def index():
return redirect(url_for("user.login"))
#user.route('/login', methods=['GET', 'POST'])
def login():
return render_template('user/login.html', content='Login Page', action=url_for('auth.authenticate'), form=LoginForm())
If, however, I change user = Blueprint('user', __name__) to user = Blueprint('user', __name__, url_prefix='/blah') it fails with a werkzeug.routing.BuildError BuildError: ('auth.authenticate', {}, None). url_for is the problem, however, I don't understand why. HALP!
Figured it out. Turns out Flask-security already has /login /logout built in and my login function was largely ignored. It wasn't used during normal app execution. Except url_for was still processed hence the BuildError.
I was trying to use an outdated example from https://github.com/dracule/FlaskBootstrapSecurity and it was a fail. Flask-Security was updated 3 mo ago. The action param should be updated to action=url_for('security.login') and it will work.
TL;DR adding a url_prefix will not use Flask-Security's built in /login /logout and a lot of vars were renamed
I know this is an old question but just in case someone has this problem as I had, here's the related documentation