I have the following codes, I'm using pyramid_beaker + gunicorn + pyramid_jinja2.
I noticed that when user is logged in, if I quickly and repeatedly do a "GET" to "http://my_server_ip_adress/addClientPersonne", I got many times a permission deny as if the logged user doesn't have "add_client" permission which is not normal. When making a "print session" I can see that sometimes the session has all the authentications informations to allow user to access the link above but another time it doesn't and the access is deny...maybe my configurations about pyramid_beaker are not good? any suggestions?
thanks.
my production.ini file
[app:main]
use = egg:annuaireldap#main
pyramid.includes = pyramid_beaker
pyramid_jinja2
session.key = annuaireldap
session.secret = iuyryoiuiytghvfs-tifrsztft
session.cookie_on_exception = true
session.type = memory
my views.py
#view_config(route_name="Menu", renderer='templates/menu.jinja2', request_method='GET')
def menu(request):
bootstrap_css_url = request.static_url('annuaireldap:static/bootstrap.min.css')
bootstrap_js_url = request.static_url('annuaireldap:static/bootstrap.min.js')
jquery_js_url = request.static_url('annuaireldap:static/jquery.min.js')
custom_css_url = request.static_url('annuaireldap:static/custom_css.css')
to_rend = {'bootstrap_css':bootstrap_css_url,'bootstrap_js':bootstrap_js_url,'jquery_js':jquery_js_url,'custom_css':custom_css_url}
to_rend.update({'Menu_1':request.route_url('addClientPersonne'),
'Menu_2':request.route_url('addClientEntreprise'),
'Menu_3':request.route_url('SeeAll')})
return to_rend
#view_config(route_name='SeeAll', renderer='templates/menu.jinja2', request_method=('GET', 'POST'))
def seeall(request):
return {}
#view_config(route_name='login', renderer='templates/login.jinja2',
request_method=('GET', 'POST'))
def login(request):
bootstrap_css_url = request.static_url('annuaireldap:static/bootstrap.min.css')
bootstrap_js_url = request.static_url('annuaireldap:static/bootstrap.min.js')
jquery_js_url = request.static_url('annuaireldap:static/jquery.min.js')
custom_css_url = request.static_url('annuaireldap:static/custom_css.css')
settings = request.registry.settings
server_uri = settings['server_uri']
rendered_form = None
base_dn_user = settings['base_dn_user']
cl = Credentials().bind(request=request)
se_connecter = deform.form.Button(name='se_connecter',
title='se connecter')
form = deform.form.Form(cl, buttons=(se_connecter,))
url_redirect = request.route_url('login')
session = request.session
session.save()
if authenticated_userid(request):
url_redirect = request.route_url("Menu")
resp = HTTPFound(location=url_redirect)
return request.response.merge_cookies(resp)
if request.method == 'POST':
if 'se_connecter' in request.POST:
try:
deserialized = form.validate(request.POST.items())
username = deserialized['username']
password = deserialized['password']
server = Server(server_uri)
user_dn = 'uid=%s,%s'%(username, base_dn_user)
user_dn = 'cn=admin,dc=splynx,dc=lan'
password = '1235789'
conn = Connection(server, user=user_dn, password=password)
if conn.bind():
session[username] = ['agent']
remember(request, username)
url_redirect = request.route_url('Menu')
resp = HTTPFound(location=url_redirect)
return request.response.merge_cookies(resp)
except ValidationFailure as e:
rendered_form = e.render()
else:
rendered_form = form.render()
return {'bootstrap_css':bootstrap_css_url,
'bootstrap_js':bootstrap_js_url,
'jquery_js':jquery_js_url,
'rendered_form':rendered_form,
'custom_css':custom_css_url}
#view_config(route_name='addClientPersonne', permission='add_client',
request_method=('GET', 'POST'), renderer='templates/addPersonne.jinja2')
def addClientPersonne(request):
bootstrap_css_url = request.static_url('annuaireldap:static/bootstrap.min.css')
bootstrap_js_url = request.static_url('annuaireldap:static/bootstrap.min.js')
jquery_js_url = request.static_url('annuaireldap:static/jquery.min.js')
custom_css_url = request.static_url('annuaireldap:static/custom_css.css')
rendered_form = None
settings = request.registry.settings
cl = ClientPersonne().bind(request=request)
ajouter = deform.form.Button(name='Ajouter',
title='Ajouter')
form = deform.form.Form(cl, buttons=(ajouter,))
request.session.save()
if request.method == 'POST':
if 'Ajouter' in request.POST:
try:
server_uri = settings['server_uri']
server = Server(server_uri)
deserialized = form.validate(request.POST.items())
nom = deserialized['nom']
prenom = deserialized['prenom']
telephone = deserialized['telephone']
description = deserialized['description']
description = "" if description == colander.null else description
creator_dn = settings['creator_dn']
creator_pwd = settings['creator_pwd']
conn = Connection(server, user=creator_dn, password=creator_pwd)
base_clients_personnes = settings['base_clients_personnes']
new_user_dn = 'uid=%s,%s'%(get_token(14), base_clients_personnes)
if conn.bind():
attributes = {'telephoneNumber':telephone,
'sn':nom,
'cn':prenom}
if description:
attributes['description'] = description
conn.add(new_user_dn, ['person', 'uidObject'], attributes)
conn.unbind()
url_redirect = request.route_url('Menu')
resp = HTTPFound(location=url_redirect)
return request.response.merge_cookies(resp)
except ValidationFailure as e:
rendered_form = e.render()
except Exception as e:
rendered_form = form.render()
else:
rendered_form = form.render()
return {'bootstrap_css':bootstrap_css_url,
'bootstrap_js':bootstrap_js_url,
'jquery_js':jquery_js_url,
'rendered_form':rendered_form,
'custom_css':custom_css_url}
my root factory
class CustomResourceFactory():
__acl__ = [
(Allow, 'agent', {'add_client', 'modify_client', 'view_client', 'delete_client'}),
DENY_ALL
]
def __init__(self, request):
print "concombre"
pass
If you have gunicorn configured to fork then you can't use an in-memory session store as it will not be shared across processes. You can confirm that this is the issue by turning off forking in gunicorn or switching to a wsgi server like waitress that does not fork.
The issue is with the gunicorn multiple workers. If you run this code with single worker it will run fine. The user session in is in memory for that worker and will not accessible from other workers.
So when you login the user details will be with only that worker and when hit the next GET call the request will go to the different worker where it will not get the user details and it will deny your request.
Related
I develop a DJango project and have develop few tests
One of these tests used to pass but do not anymore and I do not understand why
class IndexPageTestCase(TestCase):
def setUp(self):
self.client = Client()
self.pays = Pays.objects.create(pay_ide = 1,pay_nom = 'Côte d\'Ivoire',pay_abr = 'CIV')
self.region = Region.objects.create(reg_ide = 1,pay = self.pays,reg_nom = 'Region 1',reg_abr = 'RE1')
self.site = Site.objects.create(sit_ide = 1,reg=self.region,sit_typ = 'National',sit_nom = 'PA',sit_abr = 'PA')
self.user = User.objects.create_user('user','user#user.com','password')
self.profile = Profile.objects.create(user=self.user,site = self.site)
def test_index_page(self):
self.client.post('/registration/login/', {'username': 'user', 'password': 'password'})
response = self.client.get(reverse('randomization:index'))
print(response)
self.assertEquals(response.status_code,200)
print show it is not the good url (/accounts/login/?next=/randomization/ instead of /registration/login/):
<HttpResponseRedirect status_code=302, "text/html; charset=utf-8", url="/accounts/login/?next=/randomization/">
The url you pass returns a 302 which means redirect.
Your URL is good but is just redirected. set your assertEquals status code to 302
I am sending a get request in my view and then using the response to fill my database and I need some confirmation on the following:
should i make an api call inside of a view?
what should that view response be?
if i have done it wrong then what would be the right way to send get requests in Django?
my_app/views.py
class api(APIView):
template_name = 'payment/api.html'
def get(self, request):
#I SEND THE GET REQUEST HERE
config = configparser.ConfigParser()
config.read('config.ini')
r = requests.get(config['DEFAULT']['api'])
response = r.json()
#HERE I FILTER THE RESPONSE AND PUT IN A DB
for item in response:
if 'Covered Recipient Physician' in item.values():
person, _ = models.Person.objects.get_or_create(
profile_id = int(item['physician_profile_id']),
first_name = item['physician_first_name'].lower(),
last_name = item['physician_last_name'].lower()
)
address, _ = models.Address.objects.get_or_create(
business_street =
item['recipient_primary_business_street_address_line1'].lower(),
city = item['recipient_city'].lower(),
state = item['recipient_state'].lower(),
country = item['recipient_country'].lower()
)
business, _ = models.Business.objects.get_or_create(
business = item['submitting_applicable_manufacturer_or_applicable_gpo_name'].lower(),
)
business_address_link = models.Business_address_link.objects.create(
business = business,
address = address
)
business_address_link.save()
payment = models.Payment.objects.create(
record_id = int(item['record_id']),
amount = float(item['total_amount_of_payment_usdollars']),
date = item['date_of_payment'],
number_of_payments = int(item['number_of_payments_included_in_total_amount']),
payment_form = item['form_of_payment_or_transfer_of_value'],
nature_of_payment = item['nature_of_payment_or_transfer_of_value']
)
payment.save()
person_payment_information = models.Person_payment_information.objects.create(
person = person,
business_address_link = business_address_link,
payment = payment
)
person_payment_information.save()
Try to use this function for GET request -
#require_http_methods(['GET'])
def get_persons(request):
try:
data = list(Message.objects.all.values())
return render(request=request, template_name='template.html', context={"data": data})
except Exception as e:
return render(request=request, template_name='template.html', context={"error": e})
Once you get the response and send it to template.html, you can display it in any way you want.
If you want to add information to the DB you better use POST request, for example -
#require_http_methods(['POST'])
def add_person(request):
try:
data = json.loads(request.body)
new_person = Person(**data)
new_person.save()
return render(request=request, template_name='template.html', context={"data": data})
except Exception as e:
return render(request=request, template_name='template.html', context={"error": e})
I suspect it has something got to do with refresh token. Could not understand how to use it by the docs. Can I know the exact code how to use it?
The access token is created during login:
#app.route('/login', methods=['POST','GET'])
def login():
username = request.form["email"]
password = request.form["password"]
my_token_expiry_time = datetime.timedelta(seconds=60)
segments = 0
access_token = None
if request.method == 'POST':
result_set = authenticate_user(username, password)
if result_set:
ss1 = select([nsettings]).\
where(nsettings.c.mattribute == 'my_jwt_expiry_time_min')
rss1 = g.conn.execute(ss1)
if rss1.rowcount > 0:
for r in rss1:
my_token_expiry_time = datetime.timedelta(seconds=
(int(r[nsettings.c.mvalue])* 60))
else:
my_token_expiry_time = datetime.timedelta(
seconds=(2 * 60 *60)) # 2 hours
#print result_set, 'result_set result_set'
session['email'] = result_set['email']
access_token = create_access_token(
identity=username, expires_delta=my_token_expiry_time)
user_dict = result_set
if user_dict:
session['email'] = user_dict['email']
session['id'] = result_set['id']
# users and related views
session['access_token'] = access_token
print access_token, 'aaaaaaaaaaa'
return jsonify({
'email': session['email'],
'user_id': result_set['id'],
'access_token': access_token,
'id': session['id'],
}), 200
else:
return jsonify({'message': "Invalid credentials, retry"}), 401
return "True"
The flask api call to upload:
#app.route('/rt/api/v1.0/issues/<int:issue_id>/documents', methods=['POST'])
#jwt_required
def rt_doc_upload(issue_id):
'''
Upload documents for a rt ticket.
'''
# Iterate through the list of files, we don't care about the
# attribute name. We consider only the first file and ignore the
# rest.
if 'id' in session:
uploader = "3"
minternal_only = True
bool_internal_update = False
msg_str = None
for attr, document in request.files.iteritems():
trans = g.conn.begin()
try:
orig_filename = document.filename
filename, upload_folder = check_or_insert_document(
orig_filename, uploader)
new_doc = add_doc(orig_filename, filename)
print orig_filename, 'origooooo'
ins = archival_docs.insert().values(new_doc)
rs = g.conn.execute(ins)
doc_id = rs.inserted_primary_key[0]
filename = (str(doc_id) + '_' + orig_filename)
stmt = archival_docs.update().values(stored_name=filename).\
where(archival_docs.c.id == doc_id)
g.conn.execute(stmt)
document.save(os.path.join(upload_folder, filename))
mattach_doc_id = genUrl(doc_id)
trans.commit()
return jsonify(
{'issue_doc_id': rs.inserted_primary_key[0]}), 201
except Exception, e:
print e
trans.rollback()
return jsonify({'message': "Did not find any file"}), 400
return jsonify({'message': "UNAUTHORIZED"}), 401
When used with runserver and on commenting the jwt_required decorator I am able to upload and download files
Using sqlalchemy core, python and flask. The api call to upload worked for more than a month, but suddenly stopped working now
I has the following code, i try to build and microservice that allow me get specific fields in my application, am beginning with orientdb and graphql:
from flask import Flask, request
import graphene
import json
import pyorient
app = Flask(__name__)
class Person(graphene.ObjectType):
name = graphene.String()
middle_name = graphene.String()
last_name = graphene.String()
class Query(graphene.ObjectType):
person = graphene.Field(Person, id=graphene.Argument(graphene.Int))
persons = graphene.Field(Person)
def resolve_person(self, info, id):
with open('orientdb_config.json') as config_file:
orient_config = json.load(config_file)
try:
client = pyorient.OrientDB(orient_config["host"], orient_config["port"])
session_id = client.connect(orient_config["user"], orient_config["password"])
client.db_open(orient_config["database"], orient_config["user"], orient_config["password"])
if client is not None:
query = "SELECT * FROM Person WHERE #rid = #12: %(id)s" % {'id': id}
data = client.query(query)
print(data[0])
return data[0]
else:
return None
except Exception as e:
return None
def resolve_persons(self, info):
with open('orientdb_config.json') as config_file:
orient_config = json.load(config_file)
try:
client = pyorient.OrientDB(orient_config["host"], orient_config["port"])
session_id = client.connect(orient_config["user"], orient_config["password"])
client.db_open(orient_config["database"], orient_config["user"], orient_config["password"])
if client is not None:
query = "SELECT * FROM Person"
data = client.query(query)
result = []
for d in data:
result.append(d)
return result
else:
return None
except Exception as e:
return None
schema = graphene.Schema(query=Query)
#app.route("/", methods=['POST'])
def main():
data = json.loads(request.data)
return json.dumps(schema.execute(data['query']).data)
if __name__ == '__main__':
app.run(host='0.0.0.0', port=5002, debug=True)
Everything seems to work when I request a Person using its id, but when I try to obtain all the people, graphql responds with a null value, I verify the result of the query and the value is there.
In your GraphQL definition, you should have
persons = graphene.List(lambda: Person)
I am new to django, i am trying to integrate payumoney with my django project. but i am unable to integrate please anyone can give me the steps of payumoney integration.
#app.route('/flaskpayment/<cid>', methods=['GET', 'POST'])
#login_required
def flaskpayment(cid):
try:
with app.app_context():
form = PaymentForm()
if request.method == 'POST':
#read data from previous form
amount = request.form['amount']
firstname = request.form['fname']
email = request.form['email']
phone = request.form['phone']
productinfo = cid
MERCHANT_KEY = "XXXXXXX"
key="XXXXXXX"
SALT = "XXXXXXXX"
PAYU_BASE_URL = "https://test.payu.in/_payment"
posted={}
hash_object = hashlib.sha256(str(random.randint(0,20)))
txnid=hash_object.hexdigest()[0:24]
hashh = ''
posted['txnid']=txnid
hashSequence = key+'|'+txnid+'|'+amount+'|'+productinfo+'|'+firstname+'|'+email+'||||||||||'
posted['key']=key
hash_string = hashSequence
hashVarsSeq=hashSequence.split('|')
'''for i in hashVarsSeq:
try:
hash_string+=str(posted[i])
except Exception:
hash_string+='''''
hash_string+='|'
hash_string+=SALT
hashh=hashlib.sha512(hash_string).hexdigest().lower()
#Payumoney required parameters
form.key.data = MERCHANT_KEY
form.hash_string.data = hash_string
form.hash.data = hashh
form.posted.data = posted
form.firstname.data = firstname
form.email.data = email
form.txnid.data = txnid
form.amount.data = amount
form.phone.data = phone
#service_provider only for secure payment
form.service_provider.data = 'payu_paisa'
form.productinfo.data = cid
form.surl.data = 'https://www.yoursite.com/success/'
form.furl.data = 'https://www.yoursite.com/failure/'
return render_template('paymentform.html',form=form, action = PAYU_BASE_URL)
except Exception as e:
return str(e)
Please refer API documentation ,Integration doc,and website integration
here is an article you can definitely check it out for more information:-
https://makedeveasy.medium.com/payumoney-integration-with-django-rest-framework-and-javascript-19f266a6bad7