Sending multipart request by aiohttp - multipart

I trying to make test case for my view, and now I would to send mutipart request with user credentials containing user image. I use MultipartWriter but, when I'm trying to read parts, I get part as None. I'm sure that my test case is wrong written.
Thanks for your help, and sorry for my bad english.
My test case:
async def test_users_post(app):
with open('user_photo.jpg', 'rb') as file:
user_data = dict(
name='Test1',
password='Password',
grand=True,
description='Blank',
email='test#test.ru',
file=file
)
with MultipartWriter() as mpwriter:
mpwriter.append_form([(key, value) for key, value in user_data.items()])
response = await app['client'].post('/users', data=mpwriter)
assert response.status == 201
Start lines of view:
async def post(self):
reader = await self.request.multipart()
async with self.request.app['db'].acquire() as conn:
data = {}
while True:
field = await reader.next()
print(field) # field is None here
if not field:
# If not fields were read

Okay I had found way, which doesn't need multipart writer.
Now I user aiohttp.FormData for packing user credentials.
async def test_users_post(app):
form = aiohttp.FormData()
user_data = dict(
name='Test1',
password='Password',
description='Blank',
email='test#test.ru',
)
for key, value in user_data.items():
form.add_field(key, value)
form.add_field('photo', open('user_photo.jpg', 'rb'))
response = await app['client'].post('/users', data=form)
assert response.status == 201

Related

How to fix my function to obtain track ID by searching with Spotify API?

I would like to obtain the track ID from Spotify by searching with the track name. I have set up my Spotify developer account and am using spotipy. I found people with similar issues (Correct python syntax to search by artist in Spotify's Search API?) but cannot find any major differences between my code and the answers they received.
Here is my function. I am not getting any error messages, but it keeps returning "None." What should I change?
def get_id(track_name:str, token:str) -> str:
headers = {
'Accept':'application/json',
'Content-Type':'application/json',
'Authorization': 'Bearer {tokenjson}'.format(tokenjson=auth_token)
}
params = {
'q':track_name,
'type':'track'
}
try:
response = requests.get('https://api.spotify.com/v1/search',
headers = headers,
params = params
)
json = response.json()
first_result = json['tracks']['items'][0]
track_id = first_result['id']
return track_id
except:
return None

Using a synchronous celery callback in an async django channels websocket

In our django-channels async consumer, i'm trying to retrieve a group result. This result may or may not be complete, and therefor i would like to add a callback to pipe results as they become ready. The problem is, the websocket is async, the callback must be sync, and self.send method must to async. Initially i assumed being able to just wrap the async send in async_to_sync, though it gives the error You cannot use AsyncToSync in the same thread as an async event loop - just await the async function directly., and therefor it seems that going async->sync->async isn't allowed.
class ImageConsumer(AsyncWebsocketConsumer):
async def celery_retrieve_group_result(self, batch_id):
group = group = celery.GroupResult().restore(batch_id)
res = group.get(callback=self.sync_callback)
def sync_callback(self, task_id, value):
async_to_sync(self.send_group_result)(task_id, value)
async def send_group_result(self, task_id , value):
await self.send(json.dumps({"type": "result.redraw_border", "result": value}))
I have tried different combinations, though my limiting factor is that the callback must be sync, and everything else is Async.
Does anyone have experience mixing celery with async django in this manner?
Any help would be appreciated!
Decided to go with a different approach of iterating over the enclosed AsyncResults.
class ImageConsumer(AsyncWebsocketConsumer):
name = "Image Consumer"
timeout = 20
sleep_duration = 5e-2
async def celery_retrieve_group_result(self, batch_id):
group = celery.GroupResult().restore(batch_id)
if group is not None:
ordered_list_of_async_results = group.results
for result in ordered_list_of_async_results:
start = time.time()
try:
while not result.ready():
await asyncio.sleep(self.sleep_duration)
if self.timeout and time.time() - start > self.timeout:
logger.exception(str(TimeoutError))
raise TimeoutError
value = result.get()
await self.send(json.dumps({'type': 'result.processing', 'result': value}))
except:
await self.send(json.dumps({'type': 'result.processing', 'error': str(TimeoutError)}))
group.forget()
else:
await self.send(json.dumps({'type': 'response.nonexistant_group', 'error': 'No result batch exists. re-upload'}))
This is working really well. The timeout is because Celery 4.3 currently has an issue with Redis backends, which if removed will cause a gridlock. So until that is fixed, this is working perfectly.

How to allow Flutter to get a value that it stored in a firebase server or any server?

Right now I am using an http 0.11.3+16 and I am able to add a true value to an item on the site using the following function:
if (newAcceptStatus) {
response = await http.put('https://example.com/example1/${selectedOrder.id}/example2/${_authenticatedUser.id}.json?auth=${_authenticatedUser.token}',
body: json.encode(true));
this function is only called when the admin is logged in and the admin is the only one that can change the status of the Boolean, so the value is stored under the admins id and token. so I tried the following to help show if the item was changed by the admin to the user but i keep getting that the value is null when i decode the response with the following function:
Future<Null> checkAccept() async{
http.Response response;
response = await http.get('https://example.com/example1/${selectedOrder.id}/example2/(admin id goes here).json?auth=${_authenticatedUser.token}');
accepted = json.decode(response.body);
}
not sure what i am doing wrong. any help would be appreciated!
I was calling the wrong list of items which were very similar, thus giving me an empty list

How do you have a Discord bot read DMs sent to it? (discord.py)

I've come up with a way to DM people, but I want to know what they say back to the bot through DMs, as if the bot "reads" the DM, and then forwards it to some channel in a discord server of mine, or, even better, DM it to me.
Here is my starting code:
if message.content.startswith("!dm"):
if message.author.id == "[YOUR ID HERE]":
memberID = "ID OF RECIPIENT"
server = message.server
person = discord.Server.get_member(server, memberID)
await client.delete_message(message)
await client.send_message(destination = person, content = "WHAT I'D LIKE TO SAY TO THEM")
I do it a different way contrary to how people do it with defining functions, I use a more basic way of making commands.
Any help is appreciated!
Here's a quick example. I've moved your existing command into an actual Command object, so the forwarding logic is the only thing in on_message
from discord.ext import commands
bot = commands.bot('!')
# I've moved the command out of on_message so it doesn't get cluttered
#bot.event
async def on_message(message):
channel = bot.get_channel('458778457539870742')
if message.server is None and message.author != bot.user:
await bot.send_message(channel, message.content)
await bot.process_commands(message)
# This always sends the same message to the same person. Is that what you want?
#bot.command(pass_context=True)
#commands.is_owner() # The account that owns the bot
async def dm(ctx):
memberID = "ID OF RECIPIENT"
person = await bot.get_user_info(memberID)
await bot.send_message(person, "WHAT I'D LIKE TO SAY TO THEM")
await bot.delete_message(ctx.message)

ELM-LANG how to make http request when clicking on browser back button

I have an url like this /user/3 where I make a http request to get the user information.
If I move to /user/6 I will make another http request to get this user data.
My problem is when I click on the browser back button the url move back to /user/3 but it still the user 6 information which are display.
How do I do this ? Is it possible to get my old model back ? Or do I have to make again a http request to get user 3.
My urlUpdate looks like this:
urlUpdate : Result String Route -> Model -> ( Model, Cmd Msg )
urlUpdate result model =
let
currentRoute =
Routing.routeFromResult result
in
( { model | route = currentRoute }, Cmd.none )
I'm a bit lost, I don't know where to do this.
If it's not clear I would like to "catch" an event when the user click on the browser back button to get the old url and then make a http request to get again this user information.
I use the elm-navigation package.
I have try to do this in my urlUpdate:
urlUpdate : Result String Route -> Model -> ( Model, Cmd Msg )
urlUpdate result model =
let
currentRoute =
Routing.routeFromResult result
command =
case currentRoute of
Routing.HomeRoute ->
getUsers
Routing.userRoute id ->
getUser id
Routing.NotFoundRoute ->
Cmd.none
in
( { model | route = currentRoute }, command )
Which is the same thing as my init function. It doesn't work because it make an infinite loop execute the urlUpdate
Assuming you are using elm-lang/navigation module.
urlUpdate gets called when url changes (including
hitting browser navigation button).
So, one way to handle the url change can be to return
Http access command instead of Cmd.none
in the second return value of your urlUpdate function.
When the Task resolves or fails, Msg (in this example, FetchFail or FetchScucceed) will be thrown, so
that you can react by updateing your model.
In the sample below, I updated the model so that you can show spinner
until API call resolves.
sample:
urlUpdate : Result String Route -> Model -> ( Model, Cmd Msg )
urlUpdate result model =
case result of
Ok url ->
let
userId = getUserId url
in
({ model | spinner = True }, getUserInfo userId )
Err _ ->
({ model | showErr = True }, Cmd.none )
-- API call
getUserInfo : String -> Cmd Msg
getUserInfo str =
let
decodeUserInfo = Json.at ["args", "userid"] Json.string
url = "https://httpbin.org/get?userid=" ++ str
in
Task.perform FetchFail FetchSucceed (Http.get decodeUserInfo url)

Resources