Confused with the use of __init__ - python-3.x

I created a class that it's created from the YouTube API. It looks like this:
class YouTube:
def __init__(self,name,version,developerKey):
self.service=build(name, version, developerKey)
def get_video_info(self,vid_id):
vid_request = self.service.videos().list(
part = 'snippet,statistics',
id = vid_id,
fields = 'items(kind,id,statistics)')
vid_response = vid_request.execute()
return vid_response
if __name__ == "__main__":
name = 'youtube'
version = 'v3'
api_token='xxxx'
query=YouTube(name,version,api_token)
vid_id='YYYYY_VID_ID'
response = query.get_video_info(vid_id)
pprint(response)
and it works fine, but then I tried the following on the init method:
def __init__(self):
self.name = 'youtube'
self.version = 'v3'
self.developerKey = 'xxxxxxx'
self.service = build(self.name, self.version,self.developerKey)
if __name__ == "__main__":
query = YouTube()
response = query.get_video_info(vid_id)
pprint(response)
I get the following error:
def get_video_info(self,vid_id):
vid_request = self.service.videos().list(
part = 'snippet,statistics',
id=vid_id,
fields= 'items(kind,id,statistics)')
Exception has occurred: AttributeError 'str' object has no attribute 'request'
vid_response = vid_request.execute()
I searched online and I see that this Exception occurs in a variety of situation, and I feel lost? Could someone point me in which direction I should search?

According to this documentation, this is how the build function is defined:
build(serviceName, version, http=None, discoveryServiceUrl=DISCOVERY_URI, developerKey=None, model=None, requestBuilder=HttpRequest, credentials=None, cache_discovery=True, cache=None, client_options=None, adc_cert_path=None, adc_key_path=None, num_retries=1)
Construct a Resource for interacting with an API.
Therefore, you should pass the developer key as a keyword argument in your second snippet:
self.service = build(
self.name,
self.version,
developerKey = self.developerKey
)

Related

I can't get metadata from stripe session in django

I'm doing a course in udemy and there's a stripe payment lesson in django. And the problem is that today's stripe docs are different from docs from the lesson and I can't do a one thing: get an order_id from the order to make my function work correct (function change order status, save order in 'basket_history' dict and delete an actual basket). There are code from the video and my one:
views.py
Similar code:
class OrderCreateView(TitleMixin, CreateView):
title = 'Store - Оформление заказа'
template_name = 'orders/order-create.html'
form_class = OrderForm
success_url = reverse_lazy('orders:order_create')
def post(self, request, *args, **kwargs):
super().post(request, *args, **kwargs)
baskets = Basket.objects.filter(user=self.request.user)
checkout_session = stripe.checkout.Session.create(
line_items = baskets.stripe_products(),
metadata = {'order_id': self.object.id},
mode='payment',
success_url='{}{}'.format(settings.DOMAIN_NAME, reverse('orders:order_success')),
cancel_url='{}{}'.format(settings.DOMAIN_NAME, reverse('orders:order_canceled')),
)
return HttpResponseRedirect(checkout_session.url, status = HTTPStatus.SEE_OTHER)
def form_valid(self, form):
form.instance.initiator = self.request.user
return super(OrderCreateView, self).form_valid(form)
#csrf_exempt
def my_webhook_view(request):
payload = request.body
sig_header = request.META['HTTP_STRIPE_SIGNATURE']
event = None
try:
event = stripe.Webhook.construct_event(
payload, sig_header, settings.STRIPE_WEBHOOK_SECRET
)
except ValueError as e:
# Invalid payload
return HttpResponse(status=400)
except stripe.error.SignatureVerificationError as e:
# Invalid signature
return HttpResponse(status=400)
Then the difference
My code:
# Handle the checkout.session.completed event
if event['type'] == 'checkout.session.completed':
# Retrieve the session. If you require line items in the response, you may include them by expanding line_items.
session = stripe.checkout.Session.retrieve(
event['data']['object']['id'],
expand=['line_items'],
)
line_items = session.line_items
# Fulfill the purchase...
fulfill_order(line_items)
# Passed signature verification
return HttpResponse(status=200)
def fulfill_order(line_items):
order_id = int(line_items.metadata.order_id)
order = Order.objects.get(id = order_id)
order.update_after_payment()
Lesson's code:
# Handle the checkout.session.completed event
if event['type'] == 'checkout.session.completed':
# Retrieve the session. If you require line items in the response, you may include them by expanding line_items.
session = event['data']['object']
# Fulfill the purchase...
fulfill_order(session)
# Passed signature verification
return HttpResponse(status=200)
def fulfill_order(session):
order_id = int(session.metadata.order_id)
order = Order.objects.get(id = order_id)
order.update_after_payment()
So, fulfill_order doesn't work.
Help me pls and sorry for my english)
P.S. I've tried the old docs code, but id doesn't work

Why does the add_roles() method from discord.py fail here?

The following method is called on a discord bot thread from a flask application. All the print checks display the correct data so the method is being run successfully, however the final fstring
f'{role} added to {member}'
Does not get outputted to the console, which makes me think the
await member.add_roles(role)
Is not executing properly. No errors show up in the console. Every other line seems to run properly. Ive included the relevant methods below including the way the threads are structured in the flask app
client_loop = asyncio.get_event_loop()
intents = discord.Intents(messages=True, guilds=True, members=True)
client = commands.Bot(command_prefix='$', help_command=None, intents = intents)
#client.event
async def on_ready():
print(f'{client.user} is online!')
return
async def start_bot():
print(os.getenv("TOKEN"))
await client.start(os.getenv("TOKEN"))
def run_it_forever(loop):
loop.run_forever()
async def api_add_role(user, role_to_assign):
guild = client.guilds[0]
members = await guild.fetch_members(limit=None).flatten()
role = discord.utils.get(guild.roles, name=role_to_assign)
print("role")
print(role)
member = [m for m in members if m.name == user][0]
print("member")
print(member)
await member.add_roles(role)
print(f'{role} added to {member}')
app = Flask(__name__)
#app.route("/add_role")
def add_role_to_member():
name = request.args.get('name')
role = request.args.get('role')
coroutine = asyncio.run_coroutine_threadsafe(api_add_role(name, role), client_loop)
return "okay"
if __name__ == '__main__':
asyncio.get_child_watcher()
client_loop.create_task(start_bot())
botThread = threading.Thread(target=run_it_forever, args=(client_loop,))
def interrupt():
global botThread
botThread.join()
atexit.register(interrupt)
botThread.start()
print("server starting....")
app.run(host='0.0.0.0', port=5000)
I haven't seen anyone using your method to get the member object. There is get_member_named which is meant for that.
async def api_add_role(user, role_to_assign):
guild = client.guilds[0]
role = discord.utils.get(guild.roles, name=role_to_assign)
print(f"role: {role}")
member = guild.get_member_named(user) # name or name#tag
print(f"Member: {member}")
if member and role: # if both exist
await member.add_roles(role)
print(f'{role.name} added to {member.name}')

Error in django unittest: 'object has no attribute' object

I started testing views, but I found an error in the test, tell me where I went wrong, I'm just starting to learn, so don't judge strictly
my views:
`class MovieDetailView(Genre, DetailView):
model = Movie
slug_field = "url"
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context["star_form"] = RatingForm()
return context
`
my test looks like this:
`def test_starform_set_in_context(self):
request = RequestFactory().get('some-slug')
view = MovieDetailView()
view.setup(request)
context = view.get_context_data()
self.assertIn('star_form', context))`
url:
`path("<slug:slug>/", views.MovieDetailView.as_view(), name="movie_detail"),`
I think this is because Django's get_context_data() function uses the 'object' to pass it into the context.So, I suggest you to use get_object() method.
See this for more details: https://ccbv.co.uk/projects/Django/3.0/django.views.generic.detail/DetailView/
basically you need to return an object e.g.
def get_object(self,queryset=None):
obj = Movie.object.get(slug=self.kwargs.get('slug'))
return obj #also handle 404
or try one more thing :
slug_fields = slug
path should be
path("<str:slug>/", views.MovieDetailView.as_view(), name="movie_detail"),

Speed up using multi threading python3

Actually I am creating a proxy checker but the problem is it is taking a lot of time to check because there are a lot of the proxies
def proxy():
lives = []
allproxy = []
def fetch_proxy():
raw_proxy = []
res = requests.get(proxy_api)
raw_proxy = res.text.splitlines()
return raw_proxy
allproxy = fetch_proxy()
for proxy in allproxy:
try:
proxyDictChk = {
"https" : "https://"+proxy,
"http" : "http://"+proxy,
}
res = requests.get("http://httpbin.org/ip",proxies=proxyDictChk,timeout=3)
print("Proxy is Working")
lives.append(proxy)
except Exception as e:
print("Proxy Dead")
return lives
print(proxy())
I am curious that how I can use multithreading here to make this fast
PS. Thanks in advance
The python docs provide a pretty good example, https://docs.python.org/3/library/concurrent.futures.html
# We can use a with statement to ensure threads are cleaned up promptly
with concurrent.futures.ThreadPoolExecutor(max_workers=5) as executor:
# Start the load operations and mark each future with its URL
future_to_url = {executor.submit(check_proxy, url, 60): url for url in allproxy}
for future in concurrent.futures.as_completed(future_to_url):
url = future_to_url[future]
try:
is_valid = future.result()
except Exception as exc:
print('%r generated an exception: %s' % (url, exc))
else:
print('%s page is %s' % (url, is_valid))
So you would just need to define the function check_proxy.
def check_proxy( proxy ):
try:
proxyDictChk = {
"https" : "https://"+proxy,
"http" : "http://"+proxy,
}
res = requests.get("http://httpbin.org/ip",proxies=proxyDictChk,timeout=3)
print("Proxy is Working")
return True
except Exception as e:
print("Proxies Dead!")
return False
Essentially, use an executor and submit a function that does what you want. Then use the future to get the results of the functions as they're completed.
Also, since this lets the exception bubble up, you don't have to handle it in the function.
def check_proxy( proxy ):
proxyDictChk = { "https" : "https://"+proxy,
"http" : "http://"+proxy,
}
res = requests.get("http://httpbin.org/ip",proxies=proxyDictChk,timeout=3)
return True
Now the exception can be handled at the future state. You could change the return type to something more meaningful.

Custom exceptions in python starlette

I am trying to raise the custom exception using the starlette framework in python. I have the API call which checks some condtions depends on the result, it should raise exception.
I have two files app.py and error.py
#app.py
from starlette.applications import Starlette
from starlette.responses import JSONResponse
from starlette.routing import Route
from error import EmptyParamError
async def homepage(request):
a=1
b=0
if a == 1:
raise EmptyParamError(400, "status_code")
return JSONResponse({'hello': 'world'})
routes = [
Route("/", endpoint=homepage)
]
app = Starlette(routes=routes,debug=True)`
#error.py ```
from starlette.responses import JSONResponse
class BaseError(Exception):
def __init__(self, status_code: int, detail: str = None) -> None:
if detail is None:
detail = "http.HTTPStatus(status_code).phrase"
self.status_code = status_code
self.detail = detail
async def not_found(self):
return JSONResponse(content=self.title, status_code=self.status_code)
class EmptyParamError(BaseError):
""" Error is raised when group name is not provided. """
status_code = 400
title = "Missing Group Name"
When the condition is true, i want to raise the exception but its not returning the jsonrespnse but its returning the stacktrace on the console.
Please let me know if anything is wrong here
adding try block resolved the issue
try:
if a==1:
raise InvalidUsage(100,"invalid this one")
if b == 0:
raise EmptyParamError("this is empty paramuvi")
except InvalidUsage as e:
return JSONResponse({'hello': str(e.message)})
except EmptyParamError as e:
return JSONResponse({'hello': str(e.message)})

Resources