how to handle javascript callback return data in python - google-app-engine

var req = new XMLHttpRequest();
req.open('GET', '/Search?' + query, async);
if (async) {
req.onreadystatechange = function() {
if(req.readyState == 4 && req.status == 200) {
var response = null;
try {
response = JSON.parse(req.responseText);
} catch (e) {
response = req.responseText;
}
callback(response);
This callback function returns values to my python code (I am using GAE with python 2.7).
class KeywordSearchRPCHandler(webapp2.RequestHandler):
def __init__(self):
webapp2.RequestHandler.__init__(self)
self.methods = RPCMethods()
def get(self):
func = None
action = self.request.get('action')
if action:
if action[0] == '_':
self.error(403) # access denied
return
else:
func = getattr(self.methods, action, None)
if not func:
self.error(404) # file not found
return
else :
args = ()
while True:
key = 'arg%d' % len(args)
val = self.request.get(key)
#print val
if val:
args = (json.loads(val))
else:
break
result = func(*args)
self.response.out.write(json.dumps(result))
This is the code that handles the callback function.
I get the error init() takes exactly 1 argument (3 given)
Could you please help me modify my code. Thanks a lot in advance.

Here is the documentation: Docs
webapp2.RequestHandler.__init__(request=None, response=None) is the signature.
So add request and response as parameters to your init and you should be fine.
Change def __init__ (self) to def __init__(self, request=None, response=None). This will fix the bug.
And you probably want to call super properly instead of calling __init__ on the class here: webapp2.RequestHandler.__init__(self)
This should most likely be super(KeywordSearchRPCHandler, self).__init__(request, response) instead.

The init handler:
class RPCHandler(webapp2.RequestHandler):
""" Allows the functions defined in the RPCMethods class to be RPCed."""
def __init__(self, request, response):
super(RPCHandler, self).__init__(request, response)
self.methods = RPCMethods()
But I do not understand your json.loads(val) in your GET, because you send a query string and not a json request.
Below is an example post, handling a json post:
def post(self):
data = self.request.body
args = loads(data)
if 'action' not in args:
self.error(405) # access denied
return
func = args['action']
if func[0] == '_':
self.error(403) # access denied
return
func = getattr(self.methods, func, None)
if not func:
self.error(404) # file not found
return
# action handler aanroepen
result = func(args)
self.response.out.write(json.dumps(result))
If you use a GET with a query string webapp2 will handle the request. From the docs:
# An iterable with all items in the MultiDict:
# [('check', 'a'), ('check', 'b'), ('name', 'Bob')]
self.request.GET.items()

Related

object has no attribute 'to_components'

I'm trying to make a blackjack command for my Discord Bot in python, I'm making small codes and little by little testing and improving, see below:
import discord
from discord.ext import commands
from discord import app_commands
import random, json, datetime
class bj(discord.ui.Button):
def __init__(self, game ,gamesum, player_cards):
super().__init__()
self.value = None
#discord.ui.button (label="Hit", style=discord.ButtonStyle.blurple)
async def confirm(self, button: discord.ui.Button, interaction: discord. Interaction):
self.value = True
self.stop()
value_1=["A", 1,2,3,4,5,6,7,8,9,10,"J","Q","K",]
nype_1=["♦️","♠️","♥️","♣️"]
card_value_3 = random.randint(0, len(value_1) - 1)
nype_card_3 = random.randint(0, len(nype_1) - 1)
card_3 = f"{card_value_3[card_value_3]} {card_value_3[nype_card_3]}"
await match.edit()
match.edit_field(name='Your hand', value=f"{player_cards} {card_value_3}{nype_card_3}")
if type(card_value_3)==str:
if value_card_3=="A":
value_letter_3=11
else:
value_letter_3=10
else:
value_letter_3=value_card_3
class client(discord.Client):
def __init__(self):
super().__init__(intents=discord.Intents.default())
self.synced = False
async def setup_hook(self) -> None:
self.add_view(DropdownView())
async def on_ready(self):
await aclient.change_presence(activity = discord.Streaming(name = "/news", url = "https://www.youtube.com/watch?v=dQw4w9WgXcQ"))
await self.wait_until_ready()
if not self.synced:
await tree.sync()
self.synced = True
print(f"We entered as {self.user}!")
print(f"That has the ID {self.user.id}")
client = client()
tree = app_commands.CommandTree(aclient)
#tree.command(name='blackjack', description='Play a game of blackjack')
async def blackjack(interaction: discord.Interaction, amount:int):
await open_account(interaction.user)
money = await add_money(interaction.user)
if amount>money[0]:
await interaction.response.send_message(f"You don't have all this amount {interaction.user.mention}.")
else:
if quantity<0:
await interaction.response.send_message(f"You must enter a positive value")
else:
value_1=["A",2,3,4,5,6,7,8,9,10,'J','Q',"K"]
nype_1=["♦️","♠️","♥️","♣️"]
value_card_a = random.randint(0, len(value_1) - 1)
nype_card_a = random.randint(0, len(nype_1) - 1)
letter_a = f"{value_1[value_card_a]}{nype_1[nype_letter_a]}"
b_card_value = random.randint(0, len(1_value) - 1)
nype_card_b = random.randint(0, len(nype_1) - 1)
letter_b = f"{value_1[value_card_b]}{nype_1[nype_letter_a]}"
player_cards = f"{card_a} {card_b}"
if type(value_card_a)==str:
if value_card_a=="A":
value_letter_a=11
else:
value_letter_a=10
else:
value_card_a=value_card_a
if type(value_card_b)==str:
if value_card_b=="A":
value_letter_b=11
else:
value_letter_b=10
else:
value_card_b=value_card_b
sum_of_game=value_card_a+value_card_b
await add_money(interaction.user, -1*amount)
if sum_of_game==21:
result='Blackjack'
titulo_resultado=f'You won ~~K~~ {1.5*amount}'
else:
result=sum_of_game
titulo_resultado=f'You invested ~~K~~ {amount} in this blackjack'
departure=discord.Embed(
description=f'{result_title}',
colour=discord.Color.random()
)
match.add_field(name='Your hand', value=f"{player_cards}\n{result}")
if result=='Blackjack':
await add_money(interaction.user, 1.5*amount)
await interaction.response.send_message(embed=game, view=bj(game ,gamesum, player_cards))
async def open_account(user):
users = await bank_data()
if str(user.id) in users:
return False
else:
users[str(user.id)] = {}
users[str(user.id)]['wallet'] = 0
users[str(user.id)]['bank']= 0
with open("money.json", "w") as f:
json.dump(users, f)
return true
async def bank_data():
with open("money.json", "r") as f:
users = json.load(f)
return users
async def add_money(user, change=0, mode = "wallet"):
users = await bank_data()
users[str(user.id)][mode] +=change
with open("money.json", "w") as f:
json.dump(users, f)
money = [users[str(user.id)]["wallet"], users[str(user.id)]["bank"]]
return money
aclient.run(Token)
But in await interaction.response.send_message(embed=match, view=bj(match ,game_sum, player_cards)) is reporting the error
2023-02-06 19:14:31 ERROR discord.app_commands.tree Ignoring exception in command 'blackjack'
Traceback (most recent call last):
File "/home/runner/Kllin/venv/lib/python3.10/site-packages/discord/app_commands/commands.py", line 862, in _do_call
return await self._callback(interaction, **params) # type: ignore
File "main.py", line 1155, in blackjack
await interaction.response.send_message(embed=partida, view=bj(partida ,soma_de_jogo, cartas_jogador))
File "/home/runner/Kllin/venv/lib/python3.10/site-packages/discord/interactions.py", line 754, in send_message
params = interaction_message_response_params(
File "/home/runner/Kllin/venv/lib/python3.10/site-packages/discord/webhook/async_.py", line 577, in interaction_message_response_params
data['components'] = view.to_components()
AttributeError: 'bj' object has no attribute 'to_components'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/runner/Kllin/venv/lib/python3.10/site-packages/discord/app_commands/tree.py", line 1242, in _call
await command._invoke_with_namespace(interaction, namespace)
File "/home/runner/Kllin/venv/lib/python3.10/site-packages/discord/app_commands/commands.py", line 887, in _invoke_with_namespace
return await self._do_call(interaction, transformed_values)
File "/home/runner/Kllin/venv/lib/python3.10/site-packages/discord/app_commands/commands.py", line 880, in _do_call
raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'blackjack' raised an exception: AttributeError: 'bj' object has no attribute 'to_components'
I tried to interpret the error, as I recently started programming, it didn't help much, I asked in ChatGPT, and it also didn't help much (the error didn't even change), so the artificial intelligence itself suggested that I come and ask here, I hope it helps me help(Oh, and sorry for not leaving everything organized and well separated, they said there was a lot of code and little information).

How to parse array values from Json in Jmeter

For the below response I need to fetch the rideId and pass it to the next request in Jmeter.Also ,the API that generates below response should be executed until the eventType is HANDSHAKE.
[{"id":90856,"eventType":"HANDSHAKE","parameters":"{\"handshakeExpiration\":1669217518986,\"rideId\":3107}"}]
I am using the code :
import groovy.json.JsonSlurper;
def jsonSlurper=new JsonSlurper();
def apiDetailsArr=jsonSlurper.parse(prev.getResponseData())
def apiDetails=apiDetailsArr.size()>0?apiDetailsArr.get(0):null
def shouldRun = "1"
if(apiDetails!=null)
{
log.info("details",apiDetails.eventType+"")
if(apiDetails.eventType="HANDSHAKE"){
shouldRun="0"
}
def object=jsonSlurper.parseText(apiDetails.parameters)
log.info("xyz",object+"")
def id=object.rideId;
log.info("id",id+"")
vars.put("id", id+"")
}
else{
shouldRun="1"`enter code here`
}
`Condition for while controller : `${__javaScript( "${shouldRun}" != "0",)}``
All your log.info function calls cause syntax errors, you can see it yourself in (surprise!) the jmeter.log file
I fail to see where you're assigning shouldRun JMeter Variable which is used in the While Controller
Suggested code change:
import groovy.json.JsonSlurper;
def jsonSlurper = new JsonSlurper();
def apiDetailsArr = jsonSlurper.parse(prev.getResponseData())
def apiDetails = apiDetailsArr.size() > 0 ? apiDetailsArr.get(0) : null
def shouldRun = "1"
if (apiDetails != null) {
log.info("details", apiDetails.eventType + "")
if (apiDetails.eventType = "HANDSHAKE") {
shouldRun = "0"
}
def object = jsonSlurper.parseText(apiDetails.parameters)
log.info("xyz" + object)
def id = object.rideId;
log.info("id" + id)
vars.put("id", id as String)
} else {
shouldRun = "1"
}
vars.put("shouldRun", shouldRun)
More information on Groovy scripting in JMeter: Apache Groovy: What Is Groovy Used For?

Playlist playback error. Discord py. Youtube dl

I'm writing a Discord bot to play music
When trying to play a playlist, it throws the error 'Command raised an exception: KeyError: 'webpage_url'. What could be the problem?
It won't even load the first video
def __init__(self, ctx: commands.Context, source: discord.FFmpegPCMAudio, *, data: dict, volume: float = 0.5):
super().__init__(source, volume)
self.requester = ctx.author
self.channel = ctx.channel
self.data = data
self.title = data.get('title')
self.tags = data.get('tags')
self.url = data.get('webpage_url')
self.stream_url = data.get('url')
def __str__(self):
return '**{0.title}** by **{0.uploader}**'.format(self)
#classmethod
async def create_source(cls, ctx: commands.Context, search: str, *, loop: asyncio.BaseEventLoop = None):
loop = loop or asyncio.get_event_loop()
partial = functools.partial(cls.ytdl.extract_info, search, download=False, process=False)
data = await loop.run_in_executor(None, partial)
if data is None:
raise YTDLError('Couldn\'t find anything that matches `{}`'.format(search))
if 'entries' not in data:
process_info = data
else:
process_info = None
for entry in data['entries']:
if entry:
process_info = entry
break
if process_info is None:
raise YTDLError('Couldn\'t find anything that matches `{}`'.format(search))
webpage_url = process_info['webpage_url']
partial = functools.partial(cls.ytdl.extract_info, webpage_url, download=False)
processed_info = await loop.run_in_executor(None, partial)
if processed_info is None:
raise YTDLError('Couldn\'t fetch `{}`'.format(webpage_url))
if 'entries' not in processed_info:
info = processed_info
else:
info = None
while info is None:
try:
info = processed_info['entries'].pop(0)
except IndexError:
raise YTDLError('Couldn\'t retrieve any matches for `{}`'.format(webpage_url))
return cls(ctx, discord.FFmpegPCMAudio(info['url'], **cls.FFMPEG_OPTIONS), data=info)
i'm newbie. sorry for what might be a stupid question

Mocking urllib.request.urlopen using unittest

I'm trying to mock this urlopen function. Got a couple of solutions from other similar questions but none of them seems to work.
def lambda_handler(event, context):
try:
request = urllib.request.Request(url = URL, data = data, method = method, headers = headers)
with urllib.request.urlopen(request) as httpResponse:
# print(httpResponse.read().decode('utf-8'))
string = httpResponse.read().decode('utf-8')
response = json.loads(string)
print(response)
return response
Approach tried:
class mock_request():
class Request():
....
def urlopen(*args, **krwargs):
return {}
#mock.patch(.....urllib.request, mock_request)
I think the easiest way is to patch __enter__ + __exit__ methods. Just an example:
def lambda_handler(event, context):
try:
# some request... just an example
request = Request('https://restcountries.com/v3.1/name/belarus')
with urllib.request.urlopen(request) as resp:
string = resp.read().decode('utf-8')
return json.loads(string)
except Exception:
pass
Test:
from unittest import TestCase, mock
from unittest.mock import Mock
class TestExample(TestCase):
def test_lambda_handler(self):
print(lambda_handler(1, 2)) # real result from restcountries
open_mock = Mock(
# resp.read().decode('utf-8') will return static value '[]'
__enter__=Mock(return_value=Mock(read=Mock(return_value=Mock(decode=Mock(return_value='[]'))))),
__exit__=Mock(),
)
with mock.patch('urllib.request.urlopen', return_value=open_mock):
print(lambda_handler(1, 2)) # []
# resp.read().decode('utf-8') will return dynamic values
open_mock = Mock(
__enter__=Mock(
return_value=Mock(
read=Mock(return_value=Mock(decode=Mock(side_effect=[
'[{"name": "N S"}]',
'[{"name": "D G"}]']
)))
)
),
__exit__=Mock(),
)
with mock.patch('urllib.request.urlopen', return_value=open_mock):
print(lambda_handler(1, 2)) # [{"name": "N S"}]
print(lambda_handler(1, 2)) # [{"name": "D G"}]

pytest monkeypatch fails second time is called

Hi I'm trying ot use pytest to test some methods from an appengine app. Both methods use google.appengine.api.users.get_current_user to access current logged in user:
#pytest.fixture
def api_client():
tb = testbed.Testbed()
tb.activate()
tb.init_datastore_v3_stub()
tb.init_memcache_stub()
tb.init_user_stub()
ndb.get_context().clear_cache()
api.api_app.testing = True
yield api.api_app.test_client()
tb.deactivate()
def test_get_pipelines(api_client, mocked_google_user):
pips = _insert_pipelines()
user = LUser(user_id=mocked_google_user.user_id(), pipelines=[p.key for p in pips])
user.put()
r = api_client.get('/api/v1/pipelines')
assert r.status_code == 200
expected_result = {
'own': [
pips[0].to_dic(),
pips[1].to_dic(),
]
}
assert json.loads(r.data) == expected_result
def test_get_pipelines_no_pipelines(api_client, mocked_google_user):
r = api_client.get('/api/v1/pipelines')
assert r.status_code == 200
expected_result = {
'own': []
}
assert json.loads(r.data) == expected_result
I've created a pytest fixture to provide it:
#pytest.fixture(autouse=True)
def mocked_google_user(monkeypatch):
google_user = MockGoogleUser()
monkeypatch.setattr('google.appengine.api.users.get_current_user', lambda: google_user)
return google_user
It works fine for the first test but when executing ght second i thows an error like:
obj = <module 'google' from 'C:\Program Files (x86)\Google\Cloud SDK\google-cloud-sdk\platform\google_appengine\google\__init__.pyc'>
name = 'appengine', ann = 'google.appengine'
def annotated_getattr(obj, name, ann):
try:
obj = getattr(obj, name)
except AttributeError:
raise AttributeError(
'%r object at %s has no attribute %r' % (
> type(obj).__name__, ann, name
)
)
E AttributeError: 'module' object at google.appengine has no attribute 'appengine'
winvevn\lib\site-packages\_pytest\monkeypatch.py:75: AttributeError
I can't find why. Any suggestions?
I've managed to solve this by importing users locally on the test file
from google.appengine.api import users
and then monkeypatch this way:
#pytest.fixture(autouse=True)
def mocked_google_user(monkeypatch):
google_user = MockGoogleUser('test#example.com', 'test user', '193934')
monkeypatch.setattr(users, 'get_current_user', lambda: google_user)
return google_user

Resources