Currently i am working on a sample project using pydantic and starlette.
This is code from main file:
async def submit(request):
response = await request.json()
resume = Resume(**response)
JsonResponse({"Hello":"World"})
Code from Validation file:
class Basics(BaseModel):
name: str
label: str
image: str
email: str
phone: str
url: str
summary: str
location: Location
profiles: List[Profiles]
#validator('email')
def email_validation(cls, v):
regex = r'\b[A-Za-z0-9._%+-]+#[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b'
if (re.fullmatch(regex, v)):
return True
else:
raise ValueError("Email not valid")
Class Basics is a child class of class Resume. When the regex doesnt match it correctly raises a value error and internal server error is displayed in postman. But how do I return this error or some statement to postman other and prevent internal server error?
Related
New to development of API. Any help or article would really help.
my views.py
#api_view(["POST"])
def retrieve_base64_as_pdf(request):
try:
#base_64_input = request.POST.get('ImageBase64String')
body_unicode = request.body.decode('utf-8')
print(len(body_unicode))
body = json.loads(body_unicode)
print(len(body))
base_64_input = body['ImageBase64String']
doc_ref_id = body['DocRefID']
#base_64_input = json.loads(request.body["ImageBase64String"])
pdf = base64.b64decode(base_64_input)
#build PDF
with open(os.path.expanduser('life/lpo-test.pdf'), 'wb') as fout:
fout.write(pdf)
responses = single_page_extractor(file_names='life/lpo-test.pdf',client_doc_ref_id=doc_ref_id)
# return Response(responses, safe=False)
return Response(responses, status=status.HTTP_200_OK)
# responses = json.responses.replace("\'", '')
# return Response(responses, status=status.HTTP_200_OK, content_type='json')
except ValueError as e:
os.remove('life/lpo-test.pdf')
return Response(e, status=status.HTTP_400_BAD_REQUEST)
my process,
1. consume base 64 run my logic and output json.
It works 99% of the time but throws bad request at times.
1. The json input is the same for all inputs.
error message:
exception: Exception Value: Object of type ParserError is not JSON serializable
The only error:
ParserError('Error tokenizing data. C error: Expected 1 fields in line 3, saw 12\n')
Looks like Response class if from django-rest-framework and it will try to jsonify any input data you gave it.
On the last line you are trying to serialize error object and that's why you have a problem:
return Response(e, status=status.HTTP_400_BAD_REQUEST)
Try to wrap error into str to make in json-serializable:
return Response({'error': str(e)}, status=status.HTTP_400_BAD_REQUEST)
Also the problem might be in single_page_extractor if it can return error objects.
I was trying AioHttp TestCase library and just using the sample code given in the docs but it says 404 when I run pytest filename.py.
I see some examples above too, first of all I don't understand the difference between test_client and self.client. Are they both doing the same thing but just different methods?
Also, in the below implementation, where do you pass the handler info? self.client does not accept handler param hello.
from aiohttp.test_utils import AioHTTPTestCase, unittest_run_loop
from aiohttp import web
from aiohttp.test_utils import AioHTTPTestCase, unittest_run_loop
from aiohttp import web
async def hello(request):
return web.Response(text='Hello')
class MyAppTestCase(AioHTTPTestCase):
async def get_application(self):
return web.Application()
#unittest_run_loop
async def test_example(self):
request = await self.client.request("GET", "/")
assert request.status == 200
text = await request.text()
assert "Hello, world" in text
test_client fixture from pytest should be just factory that make is the same as AioHTTPTestCase.client
When I look to code in TestClient it all got down to cal _request that looks like this:
async def _request(
self,
method: str,
str_or_url: StrOrURL, *,
params: Optional[Mapping[str, str]]=None,
data: Any=None,
json: Any=None,
cookies: Optional[LooseCookies]=None,
headers: LooseHeaders=None,
skip_auto_headers: Optional[Iterable[str]]=None,
auth: Optional[BasicAuth]=None,
allow_redirects: bool=True,
max_redirects: int=10,
compress: Optional[str]=None,
chunked: Optional[bool]=None,
expect100: bool=False,
raise_for_status: Optional[bool]=None,
read_until_eof: bool=True,
proxy: Optional[StrOrURL]=None,
proxy_auth: Optional[BasicAuth]=None,
timeout: Union[ClientTimeout, object]=sentinel,
verify_ssl: Optional[bool]=None,
fingerprint: Optional[bytes]=None,
ssl_context: Optional[SSLContext]=None,
ssl: Optional[Union[SSLContext, bool, Fingerprint]]=None,
proxy_headers: Optional[LooseHeaders]=None,
trace_request_ctx: Optional[SimpleNamespace]=None
) -> ClientResponse:
So you can pass these to client and it will make the call. data and json should be the same (expecting as in requests it is like so), json just dumps it.
So something like this should work. At least for me:
class BookingTest(AioHTTPTestCase):
async def get_application(self):
return await create_test_app()
#unittest_run_loop
async def test_create_booking(self):
data = {
"my_id": "1234"
}
# the post data should be in request.body
# (we use connexion and we have it parsed as an argument to handler named body)
resp = await self.client.request("POST", "/api/bookings", json=data)
assert resp.status == 201
#unittest_run_loop
async def test_get_booking(self):
booking_id = "1234"
url = f"/be/api/bookings/{booking_id}"
resp = await self.client.request("GET", url)
assert resp.status == 200
I'm attempting to use a script I found online, (https://confluence.atlassian.com/display/DOCSPRINT/The+Simplest+Possible+JIRA+REST+Examples) probably 5+ years old, to access Jira REST API. I have all the modules installed in Pyhton 2.7. However, when run the script I get an error that SimplePool cannot be imported. Having done my Goodiligence (Google searching), I see that SimplePool is deprecated in restkit 4.2.2 (which is the version I have installed). So, the doc that I found (http://pydoc.net/Python/restkit/2.3.0/restkit.pool.simple/) says to use TConnectionManager (which I did with no success). I still get a similar error. So, I stumbled upon another doc (http://benoitc.github.io/restkit/pool.html) and it says to use ConnectionPool, and I still get a similar error. I appreciate any direction given. Here is my code:
import simplejson as json
from restkit import * #added this line after finding the last document
from restkit import Resource, BasicAuth, request
from socketpool import ConnectionPool
SimplePool = ConnectionPool
def rest_test(server_base_url, user, password, issue_key):
'''
Use restkit to make a REST request to JIRA
'''
verbose = False
# A pool of connections
pool = SimplePool(factory=Connection)
# This sends the user and password with the request.
auth = BasicAuth(user, password)
resource_name = "issue"
complete_url = "%s/rest/api/latest/%s/%s" % (server_base_url, resource_name, issue_key)
resource = Resource(complete_url, pool_instance=pool, filters=[auth])
try:
response = resource.get(headers = {'Content-Type' : 'application/json'})
except Exception,ex:
# ex.msg is a string that looks like a dictionary
print "EXCEPTION: %s " % ex.msg
return
# Most successful responses have an HTTP 200 status
if response.status_int != 200:
print "ERROR: status %s" % response.status_int
return
# Convert the text in the reply into a Python dictionary
issue = json.loads(response.body_string())
# Pretty-print the JSON
if verbose:
print json.dumps(issue, sort_keys=True, indent=4)
# The properties of the issue include:
# self, html, key, transitions, expand, fields
print "Issue key: %s" % issue['key']
fields = issue['fields']
for field_name in fields:
field_object = fields[field_name]
print "Field %s = %s" % (field_name, field_object['type'])
# The type of the value of a field depends on the type of the field
if field_name in ["summary"]:
print " Value = %s" % field_object['value']
if __name__ == '__main__':
user = 'myuname'
password = '*****'
server_url = 'http://jira.mysite.com/'
issue_key = 'JRA-219'
rest_test(server_url, user, password, issue_key)
Here is the error returned:
File "simplest_client.py", line 30, in rest_test
pool = SimplePool()
TypeError: __init__() takes at least 2 arguments (1 given)
EXCEPTION: <?xml version="1.0" encoding="UTF-8" standalone="yes"?><status><status-code>404</status-code><message>null for uri: http://jira.mysite.com//rest/api/latest/issue/JRA-219</message></status>
Am working with sleekxmpp with python for sending messages and its working perfectly.Now i need to implement same in django to create web api for my mobile application.
When i implement that code in django its not getting connected to ejabberd server.xmpp=self.aaaa(jid,password,receiver,message) this function is throughing none value.
Below is my code in django:
class SendMessageView(APIView,sleekxmpp.ClientXMPP):
def aaaa(self,jid, password, recipient, message):
print "dddddddddddddddddddddddddddddddd",jid,password
sleekxmpp.ClientXMPP.__init__(self, jid, password)
self.recipient = recipient
self.msg = message
self.add_event_handler("session_start", self.start)
def start(self, event):
self.send_presence()
try:
self.get_roster()
except IqError as err:
logging.error('There was an error getting the roster')
logging.error(err.iq['error']['condition'])
self.disconnect()
except IqTimeout:
logging.error('Server is taking too long to respond')
self.disconnect()
self.send_message(mto=self.recipient,mbody=self.msg,mtype='chat')
self.disconnect(wait=True)
def post(self,request,format=None):
serializer=SendMessageSerializer(request.DATA)
jid=request.DATA.get('sender')
password=request.DATA.get('password')
receiver=request.DATA.get('receiver')
message=request.DATA.get('message')
print "ddddddddddddd",jid,password,receiver,message
xmpp=self.aaaa(jid,password,receiver,message)
print "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",xmpp
xmpp.register_plugin('xep_0030')
xmpp.register_plugin('xep_0199')
if xmpp.connect():
xmpp.process(block=False)
print "Connected"
else:
print "Not Connected"
Error shown is:
AttributeError at /chat-message/send/
'NoneType' object has no attribute 'register_plugin'
Request Method: POST
Request URL: ******/chat-message/send/
Django Version: 1.6
Exception Type: AttributeError
Exception Value:
'NoneType' object has no attribute 'register_plugin'
Exception Location: /home/ntech/projects/project_path/apps/chats/views.py in post, line 58
Python Executable: /home/ntech/Virtualenv/project_path/bin/python
Python Version: 2.7.6
Python Path:
['/home/ntech/projects/chatline',
'/home/ntech/Virtualenv/project_path/lib/python2.7',
'/home/ntech/Virtualenv/project_path/lib/python2.7/plat-i386-linux-gnu',
'/home/ntech/Virtualenv/project_path/lib/python2.7/lib-tk',
'/home/ntech/Virtualenv/project_path/lib/python2.7/lib-old',
'/home/ntech/Virtualenv/project_path/lib/python2.7/lib-dynload',
'/usr/lib/python2.7',
'/usr/lib/python2.7/plat-i386-linux-gnu',
'/usr/lib/python2.7/lib-tk',
'/home/ntech/Virtualenv/project_path/local/lib/python2.7/site-packages',
'/home/ntech/Virtualenv/project_path/lib/python2.7/site-packages']
Server time: Mon, 29 Dec 2014 06:02:10 +0000
Your method aaaa always return None. Try to use self.
Also it is not a good idea to multiple inheritance here. Try aggregation
class SendMessageView(APIView):
def aaaa(self,jid, password, recipient, message):
...
self.xmpp = sleekxmpp.ClientXMPP(jid, password)
...
def post(self,request,format=None):
...
self.aaaa(jid,password,receiver,message)
self.xmpp.register_plugin('xep_0030')
self.xmpp.register_plugin('xep_0199')
...
Or even better:
class SendMessageView(APIView):
def get_xmpp(self,jid, password, recipient, message):
...
return sleekxmpp.ClientXMPP(jid, password)
...
def post(self,request,format=None):
...
xmpp = self.get_xmpp(jid,password,receiver,message)
xmpp.register_plugin('xep_0030')
xmpp.register_plugin('xep_0199')
...
I'm newbie in Django tests. How to create Unit Test for this views function? My unit test function should import function from views? Please an example. This will help me to understand how it work
#maintainance_job
def time_to_end(request):
today = datetime.date.today()
datas = Data.objects.filter(start__lte=today,
other_date__gte=today)
for data in datas:
subject = _(u'Send email')
body = render_to_string('mail.txt',
{'data': data})
email = EmailMessage(subject, body,
'admin#admin.com',
[data.user.email])
email.send()
return HttpResponse('Done')
urls:
(r'^maintainance/jobs/time_to_end/$', 'content.views.time_to_end'),
There is a simpliest test for your case (place it in tests.py of a directory where is your view function):
from django.utils import unittest
from django.test.client import Client
class HttpTester( unittest.TestCase ):
def setUp( self ):
self._client = Client() # init a client for local access to pages of your site
def test_time_to_end( self ):
response = self._client.get( '/jobs/time_to_end/' )
# response = self._client.post( '/jobs/time_to_end/' ) - a 'POST' request
result = response.content
assert result != 'Done'
So, we use self._client to make 'get' and 'post' requests. Responses can be accessed by reading response.content (the full text of response) or by reading response.context if you use templates and want to access variables passing to the templates.
For example if your view normally must pass the dict with context variable 'result' to template:
{ 'result': "DONE" }
then you could check your result:
result = response.context[ 'result' ]
assert result != 'Done'
So, you wait your test will have the 'result' variable and it will be 'Done'. Otherwise you raise AssertionError (note assert statement).
If there is an exception then tests fails. AssertionError is an exception too.
More details - in the docs and in a book "Dive into Python".