I am trying to make UploadFile optional in FastAPI, in the process, I am able to make a single file optional, but got an error if I convert it to multiple files.
# Making optional for single uploadfile
#app.post("/optional-file")
async def optionalFile(file: Optional[UploadFile] = File(None)):
if not file:
print("no file")
return "no file"
print(file.filename)
return {"name": file.filename}
# Making optional for multiple uploadfile
#app.post("/optional-files")
async def optionalFiles(files: Optional[List[UploadFile]] = File(None)):
if not files:
print("no files")
return "no files"
print(file[0].filename)
return {"name": file[0].filename}
and I am getting this error in return.
{"detail":[{"loc":["body","files",0],"msg":"Expected UploadFile, received: <class 'str'>","type":"value_error"}]}
Thanks in advance for any sort of help provided.
I solved it with:
def get_files(files_list: List[Union[UploadFile, str]] = File(None)):
if isinstance(files_list, str):
files_list = []
I send '', if i have no files to send.
Related
I am trying to write unit test case for an external facing api of my Django application. I have a model called Dummy with two fields temp and content. The following function is called by third party to fetch the content field. temp is an indexed unique key.
#csrf_exempt
def fetch_dummy_content(request):
try:
temp = request.GET.get("temp")
dummy_obj = Dummy.objects.get(temp=temp)
except Dummy.DoesNotExist:
content = 'Object not found.'
else:
content = dummy_obj.content
return HttpResponse(content, content_type='text/plain')
I have the following unit test case.
def test_dummy_content(self):
params = {
'temp': 'abc'
}
dummy_obj = mommy.make(
'Dummy',
temp='abc',
content='Hello World'
)
response = self.client.get(
'/fetch_dummy_content/',
params=params
)
self.assertEqual(response.status_code, 200)
self.assertEqual(response.content, 'Hello World')
Every time I run the test case, it goes into exception and returns Object not found. instead of Hello World. Uponn further debugging I found that temp from request object inside view function is always None, even though I am passing it in params.
I might be missing something and not able to figure out. What's the proper way to test these kind of functions.
There's no params parameter for the get or any of the other functions on the client, you're probably thinking of data.
response = self.client.get(
'/fetch_dummy_content/',
data=params
)
It's the second argument anyway, so you can just do self.client.get('/fetch_dummy_content/', params) too.
Any unknown parameters get included in the environment which explains why you were not getting an error for using the wrong name.
I'm using the following code (from django management commands) to listen to the Twitter stream - I've used the same code on a seperate command to track keywords successfully - I've branched this out to use location, and (apparently rightly) wanted to test this out without disrupting my existing analysis that's running.
I've followed the docs and have made sure the box is in Long/Lat format (in fact, I'm using the example long/lat from the Twitter docs now). It looks broadly the same as the question here, and I tried using their version of the code from the answer - same error. If I switch back to using 'track=...', the same code works, so it's a problem with the location filter.
Adding a print debug inside streaming.py in tweepy so I can see what's happening, I print out the self.parameters self.url and self.headers from _run, and get:
{'track': 't,w,i,t,t,e,r', 'delimited': 'length', 'locations': '-121.7500,36.8000,-122.7500,37.8000'}
/1.1/statuses/filter.json?delimited=length and
{'Content-type': 'application/x-www-form-urlencoded'}
respectively - seems to me to be missing the search for location in some way shape or form. I don't believe I'm/I'm obviously not the only one using tweepy location search, so think it's more likely a problem in my use of it than a bug in tweepy (I'm on 2.3.0), but my implementation looks right afaict.
My stream handling code is here:
consumer_key = 'stuff'
consumer_secret = 'stuff'
access_token='stuff'
access_token_secret_var='stuff'
import tweepy
import json
# This is the listener, resposible for receiving data
class StdOutListener(tweepy.StreamListener):
def on_data(self, data):
# Twitter returns data in JSON format - we need to decode it first
decoded = json.loads(data)
#print type(decoded), decoded
# Also, we convert UTF-8 to ASCII ignoring all bad characters sent by users
try:
user, created = read_user(decoded)
print "DEBUG USER", user, created
if decoded['lang'] == 'en':
tweet, created = read_tweet(decoded, user)
print "DEBUG TWEET", tweet, created
else:
pass
except KeyError,e:
print "Error on Key", e
pass
except DataError, e:
print "DataError", e
pass
#print user, created
print ''
return True
def on_error(self, status):
print status
l = StdOutListener()
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret_var)
stream = tweepy.Stream(auth, l)
#locations must be long, lat
stream.filter(locations=[-121.75,36.8,-122.75,37.8], track='twitter')
The issue here was the order of the coordinates.
Correct format is:
SouthWest Corner(Long, Lat), NorthEast Corner(Long, Lat). I had them transposed. :(
The streaming API doesn't allow to filter by location AND keyword simultaneously.
you must refer to this answer i had the same problem earlier
https://stackoverflow.com/a/22889470/4432830
Unfortunately there's no way to create a user in Intercom.io with a tag, so I'm trying to write some code that will look for an existing tag in Intercom, and if it's there, add a user to that tag, and if it's not, create the tag and add the user to it. I've tried several different variations by looking at the docs for the python-intercom library, but there are conflicting methods (Intercom.update_tag vs. Tag.update), and nothing has worked yet.
Here's how users are created in Intercom (this works):
import time
from members.models import Member
from intercom import Intercom, Tag
Intercom.app_id = settings.INTERCOM_TEST_APP_ID
Intercom.api_key = settings.INTERCOM_TEST_API_KEY
member = Member.objects.get(email="exampleemail#example.com")
Intercom.create_user(
email=member.email,
user_id=member.email,
name="%s %s" % (member.first_name, member.last_name),
created_at=int(time.time()),
city_name=member.city,
last_seen_ip=member.last_ip,
)
Here's what I currently have to look for and create or update tags, which triggers no errors, but doesn't successfully tag the user:
tag = Intercom.get_tag(name=member.referral_code)
if tag['id'] != None:
Intercom.update_tag(member.referral_code, "tag", user_ids=[member.pk])
else:
Intercom.create_tag(tag, "tag", user_ids=[member.pk])
I've also tried variations of the following, but it gets the error "descriptor 'update' requires a 'dict' object but received a 'unicode':
if Tag.find_by_name(member.referral_code) != 0:
Tag.update(member.referral_code, "tag", user_ids=[member.pk])
else:
Tag.create(member.referral_code, "tag", user_ids=[member.pk])
What do I need to change to get tagging to work?
My name's Jeff, I'm one of the customer success engineers at Intercom. Unfortunately the intercom-python library is still using our deprecated V1 API which is likely causing some of the confusion here. Until that library updates to use our newer REST API I would suggest that you use the python requests library and call our API directly. I've got minimal python experience but something like this should get you started on the right track.
import requests
from requests.auth import HTTPBasicAuth
import json
tags_url = 'https://api.intercom.io/tags'
app_id = 'YOUR_APP_ID'
api_key = 'YOUR_API_KEY'
headers = {'content-type': 'application/json', 'Accept': 'application/json'}
tag_name = 'My sweet tag'
# Get tags to then loop through
list_tag_response_as_json = requests.get(tags_url, auth=(app_id, api_key), headers=headers).json()
tag_names = [tag['name'] for tag in list_tag_response_as_json['tags']]
if tag_name not in tag_names
# Create a tag
tag_response = requests.post(tags_url, auth=(app_id, api_key), headers=headers, data={'name': tag_name})
# Tag users
tag_and_users = {'name':tag_name, 'users': [{'email': 'abc#example.com'}, {'email': 'def#example.com'}]}
tagged_user_response = requests.post(tags_url, auth=(app_id, api_key), headers=headers, data=tag_and_users)
Also, feel free to give us a shout in Intercom if you're still having trouble and we can help you there.
I find this error to happen to many other users and although trying many of suggested solutions nothing seems to work, so I'm trying to post my specific case.
I'm trying to save an image from iphone application to my postgresql database using django.
my view looks like this:
def objectimages(request, obj_id):
object = imagesTable.objects.filter(uniqueid=obj_id)
if request.method == 'POST':
value = request.POST.get('image')
f= open('image.txt', 'w+')
f.write(value)
f.close()
object.update(image=value)
return HttpResponse("Post received")
elif request.method == 'GET':
output = serializers.serialize('json',object, fields=('image'),indent=5, use_natural_keys=True)
return HttpResponse(output, content_type="application/json")
the file is just for debug purposes and it seems to write the correct data
also tried return HttpResponse({}, content_type="application/json")
in my application the post request is done using AFNetworking like this:
-(void) saveImageToDB
{
NSString* BaseURLString = POST_IMAGE;
NSData* data = UIImagePNGRepresentation(self.image);
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[manager POST:BaseURLString
parameters:#{#"image":[data base64EncodedString]}
success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"image saved successfuly");
}
failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error saving image: %#", error)
}];
}
so I added this line of code
manager.responseSerializer = [AFJSONResponseSerializer serializerWithReadingOptions:NSJSONReadingAllowFragments];
and got this error: Invalid value around character 1
I also try to do:
AFJSONRequestSerializer *requestSerializer = [AFJSONRequestSerializer serializer];
[requestSerializer setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[requestSerializer setValue:#"application/json" forHTTPHeaderField:#"Accept"];
manager.requestSerializer = requestSerializer;
which ended up always with The request timed out.
please advice what is wrong with my request
You're returning the string Post received as a response to POST requests. This string is not valid JSON (if you wanted to return just a string in your JSON response, the correct JSON representation would be "Post received", with quotes), and your JSON deserializer seems to complain about exactly that. Try serializing your response in both branches of your logic.
In my djang urls pattern file, I'd like to hold a bunch of sub-url's but I don't want to make it ugly.
I have a file which handles all of my Ajax requests (it outputs different JSON files depending on the request it gets.
example (in my url.py):
in the form: (url, maps to)
(ajax/do_a, ajax.do_a)
ajax/do_b, ajax.do_b)
ajax/do_c, ajax.do_c)
ajax/do_d, ajax.do_d)
these are all sub-urls, eg.
mywebsite.com/ajax/do_a
mywebsite.com/ajax/do_b
etc.
Basically do_a,do_b,do_c,and do_d are all different request handlers sitting in the same same in the "ajax.py" file. I really don't want to be filling up my urls.py file with all of these urls for ajax requests. I was thinking of move this so that I only have
ajax/
in my url.py file and then somehow parse the ajax/ request url in my request handler (in the ajax.py file) so I can see what string came after the "ajax/". I'm not sure how to do this or if this would be a good idea to do this....Could anyone offer some advice? thanks :)
You could set up a dispatcher view for handling these. For example, in your urls.py:
(r'^ajax/do_(?P<do_token>(\d+))/$', 'do_dispatcher', {}, "di_dispatcher"),
Then, give yourself a view to handle it:
def do_a(request):
pass
def do_b(request):
pass
def do_c(request):
pass
DO_LOOKUP = {
'a' = do_a,
'b' = do_b,
'c' = do_c,
}
def do_dispatch(request, do_token):
do_func = DO_LOOKUP.get(do_token, None)
if do_func is None:
return HttpResponseNotFound("No do could be found for token '%s'!" % do_token)
else:
return do_func(request)