I am making some API calls from an external source but would like to make it dynamic instead of manually putting the reference number in my views in the DRF UI provided.
What I want is that in my DRF UI, I should have a field whereby when I enter a reference number, I should get the response from from the API, I am successfully doing this manually but I want to make it dynamic from the DRF UI.
I would also like to get a better formatted JSON Response in my DRF UI. An image is below to better explain what I meant
Views.py
class Paystack(APIView):
def get(self, request):
url = "https://api.paystack.co/transaction/verify/{{REFERENCE_NO}}"
payload = {}
files = {}
headers = {
'Authorization': 'Bearer SECRET_KEY',
'Content-Type': 'application/json'
}
response = requests.request("GET", url, headers=headers, data= payload, files=files)
return Response(response)
def post(self, request):
url = "https://api.paystack.co/transaction/verify/{{REFERENCE_NO}}"
payload = {}
files = {}
headers = {
'Authorization': 'Bearer SECRET_KEY',
'Content-Type': 'application/json'
}
response = requests.request("GET", url, headers=headers, data= payload, files=files)
return Response(response)
urls.py
from django.urls import path, include
from .views import *
from rest_framework.routers import DefaultRouter
router = DefaultRouter()
router.register('paystack', Paystack, basename='paystack')
urlpatterns = [
path('paystack/', Paystack.as_view(), name='paystack'),
]
Presently, my DRF UI looks likes this,
If you want to be able to get reference_id in your DRF UI, you must either define a serializer and catch the value from that, or, you can define a URL pattern which asks for a reference ID.
You can do this
In urls.py
urlpatterns = [
path('paystack/<str:reference_id>', Paystack.as_view(), name='paystack'),
]
In your views.py
class Paystack(APIView):
def get(self, request, reference_id):
url = f"https://api.paystack.co/transaction/verify/{reference_id}"
payload = {}
files = {}
headers = {
'Authorization': 'Bearer SECRET_KEY',
'Content-Type': 'application/json'
}
response = requests.request("GET", url, headers=headers, data= payload, files=files)
return Response(response)
Related
import requests
import random
m_otp=str(random.randint(100000,999999))
print(m_otp)
url = "https://ziper.io/api/send.php?instance_id=My_instance_id&access_token=My_Acess_token&type=json&number=919XXXXXXXXX"
payload = "{\r\n \"text\": \"Hello there \"\r\n }"
headers = {}
response = requests.request("POST", url, headers=headers, data=payload)
print(response.text)
I tried solutions from github but there is the thing I'm getting it.
Do you think of something like:
import requests
import random
import json
m_otp=str(random.randint(100000,999999))
print(m_otp)
url = "https://ziper.io/api/send.php?instance_id=My_instance_id&access_token=My_Acess_token&type=json&number=919XXXXXXXXX"
payload = {"text": "Hello there", "m_otp":m_otp}
payload_str = json.dumps(payload)
headers = {}
response = requests.request("POST", url, headers=headers, data=payload_str)
print(response.text)
?
If not, feel free to tell me the issue and I'll edit my answer.
Also, shouldn't m_otp get passed as a int ?
``I have tried method1
Given url urlUP + querykey
And header Authorization = auth.getBearerToken('Profile',keyClock)
And multipart file files = { read: '#(file1)' , read: '#(file2)' , read: '#(file3)' , read: '#(file4)' , contentType: 'application/json' }
When method post
Then status 200
method2
* def filepathtblBooking = 'src/test/file1.json'
* def filepathtblStatus = 'src/test/file2.json'
* def filepathtblBuilding = 'src/test/file3.json'
* def filepathtblRoom = 'src/test/file4.json'
Given url urlUP + querykey
And header Authorization = auth.getBearerToken('Profile',keyClock)
And multipart file files = { read: '#(file1)' , contentType: 'application/json' }
And multipart file files = { read: '#(file2)' , contentType: 'application/json' }
And multipart file files = { read: '#(file3)' , contentType: 'application/json' }
And multipart file files = { read: '#(file4)' , contentType: 'application/json' }
When method post
Then status 200
both failed
i have tried both ways API is not hit
Refer documentation: https://github.com/karatelabs/karate#multipart-files
And here is an example.
If you mean an array of files with the same name, we just realized this is not supported, but this will be available in the next release.
I am a beginner in Django. I want to send an email on button click. Button is delete button. when press on delete button, i want to send an email to receiver#gmail.com.
As per the below code, email send when the page loaded. And also there was an internal server error. could you please help me to change the as email send on button click.
views.py
class delete_profile(View):
print("nothing")
def post(self, request, *args, **kwargs):
print("nothing")
template = loader.get_template("frontend/subscription-start.html")
email_content = "deletion confirmation"
send_mail(
'No Dowry Marriage - Subscription',
email_content,
'sender#gmail.com',
['reciever#gmail.com'],
html_message=email_content,
fail_silently=False
)
urls.py
path('delete_profile', csrf_exempt(delete_profile.as_view()), name='delete_profile')
user_profile.html
<script>
function delete_profile1() {
var csrftoken = getCookie('csrftoken');
console.log("rhgrjhrj")
$.ajax({
type: 'POST',
url: '{% url "delete_profile" %}',
data: {
csrfmiddlewaretoken: csrftoken
},
success: function () {
toastr.info('Preference Updated Successfully')
}
});
}
</script>
THANKS IN ADVANCE!!!!
first you import JsonResponse and render in your views.py:
from django.http import JsonResponse
from django.shortcuts import render
After change your Class:
class delete_profile(View):
def get(self, request, *args, **kwargs):
# handle the get request
return render(request, 'frontend/subscription-start.html')
def post(self, request, *args, **kwargs):
email_content = "deletion confirmation"
send_mail(
'No Dowry Marriage - Subscription',
email_content,
'sender#gmail.com',
['reciever#gmail.com'],
html_message=email_content,
fail_silently=False
)
return JsonResponse({'some_text': some_text})
# or
# return render(request, 'some_location/some_html_file')
Maybe change your ajax POST request headers:
headers: {
'X-CSRFToken': csrftoken
}
I have an APIVIEW in DRF which I have written some views in it to get some Response, I would like to get a better formatted JSONResponse.
Views.py
class Pay(APIView):
def get(self, request):
url = "https://api.paystack.co/transaction/verify/262762380"
payload = {}
files = {}
headers = {
'Authorization': 'Bearer SECRET_KEY',
'Content-Type': 'application/json'
}
response = requests.request("GET", url, headers=headers, data= payload, files=files)
return Response(response)
This is a pictorial representation of the bad formatted JSONResponse I am getting which I would like to improve. Thanks
So in the case you don't have a Model but rather some data structure you get in some other way (as in a response from a third party API) just return a Response with this data structure as argument.
In this case you are effectively acting as a kind of proxy between the 3rd party API and your client, if that is what you intend (be sure not to leak private data!)
Example:
class Pay(APIView):
def get(self, request):
url = "https://api.paystack.co/transaction/verify/262762380"
payload = {}
files = {}
headers = {
'Authorization': 'Bearer SECRET_KEY',
'Content-Type': 'application/json'
}
# no need for 'data' and 'files' arguments with method GET
response = requests.get(url, headers=headers)
# do some validation, at least check for response.status_code
if response.status_code == 200:
data = response.json()
return Response(data)
There are many more possibilities when using the requests library.
Right now I am currently just doing this:
self.response.headers['Content-Type'] = 'application/json'
self.response.out.write('{"success": "some var", "payload": "some var"}')
Is there a better way to do it using some library?
Yes, you should use the json library that is supported in Python 2.7:
import json
self.response.headers['Content-Type'] = 'application/json'
obj = {
'success': 'some var',
'payload': 'some var',
}
self.response.out.write(json.dumps(obj))
webapp2 has a handy wrapper for the json module: it will use simplejson if available, or the json module from Python >= 2.6 if available, and as a last resource the django.utils.simplejson module on App Engine.
http://webapp2.readthedocs.io/en/latest/api/webapp2_extras/json.html
from webapp2_extras import json
self.response.content_type = 'application/json'
obj = {
'success': 'some var',
'payload': 'some var',
}
self.response.write(json.encode(obj))
python itself has a json module, which will make sure that your JSON is properly formatted, handwritten JSON is more prone to get errors.
import json
self.response.headers['Content-Type'] = 'application/json'
json.dump({"success":somevar,"payload":someothervar},self.response.out)
I usually using like this:
class JsonEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, datetime):
return obj.isoformat()
elif isinstance(obj, ndb.Key):
return obj.urlsafe()
return json.JSONEncoder.default(self, obj)
class BaseRequestHandler(webapp2.RequestHandler):
def json_response(self, data, status=200):
self.response.headers['Content-Type'] = 'application/json'
self.response.status_int = status
self.response.write(json.dumps(data, cls=JsonEncoder))
class APIHandler(BaseRequestHandler):
def get_product(self):
product = Product.get(id=1)
if product:
jpro = product.to_dict()
self.json_response(jpro)
else:
self.json_response({'msg': 'product not found'}, status=404)
import json
import webapp2
def jsonify(**kwargs):
response = webapp2.Response(content_type="application/json")
json.dump(kwargs, response.out)
return response
Every place you want to return a json response...
return jsonify(arg1='val1', arg2='val2')
or
return jsonify({ 'arg1': 'val1', 'arg2': 'val2' })