Cloud Endpoints - Google Glass object has no attribute 'mirror_service' - google-cloud-endpoints

I'm attempting to incorporate cloud enpoints into my app, I'm currently using the Python Quickstart for proof of concept. I'm having an issue when I attempt to call a method to send a card to my glass. Below is my code, please ignore the indentation is missing.
#endpoints.api(name='tasks', version='v1',
description='API for TaskAlert Management',
allowed_client_ids=[CLIENT_ID, endpoints.API_EXPLORER_CLIENT_ID])
class TaskAlertApi(remote.Service):
#endpoints.method(Task, Task,
name='task.insert',
path='tasker',
http_method='POST')
def insert_task(self, request):
TaskModel(author=request.author, content=request.content, date=request.date).put()
themirror = MainHandler()
themirror._insert_map_with_distance_from_home()
return request
So when "themirror._insert_map_with_distance_from_home()" is called I am getting the following error. Does anyone have any suggestions? I am trying to call this from myappspot.com/_ah/api/explorer.
in _insert_map_with_distance_from_home
self.mirror_service.timeline().insert(body=body).execute()
AttributeError: 'MainHandler' object has no attribute 'mirror_service'

I'm afraid you will have to rethink your code quite a bit for this but I'll try to get the basics explained here.
The main problem is that the MainHandler does quite a bit when actually receiving a HTTP request. The most important thing is what happens in the #util.auth_required decorator of the MainHandler's get method, which actually creates the mirror_service, authenticated for the current user. When you access the MainHandler directly from your code, none of this actually happens, so there is no mirror_service available (which results in the error you get).
Since the way endpoints are called is quite different from the way normal RequestHandlers are called, you also can't rely on stored session credentials or similar to match an Endpoints User to the Mirror User.
Basically what you would have to do is to create a new mirror_service inside of your endpoint method.
For this you will have to call your API authenticated (adding the Mirror API scopes to the authentication scopes). You can then extract the used access_token from the request header and use this access_token to create OAuth2Credentials to create the mirror_service.
Some code snippets without promises of completeness since it's hard to tell without knowing your actual code:
import os
from oauth2client.client import AccessTokenCredentials
# extract the token from request
if "HTTP_AUTHORIZATION" in os.environ:
(tokentype, token) = os.environ["HTTP_AUTHORIZATION"].split(" ")
# create simple OAuth2Credentials using the token
credentials = AccessTokenCredentials(token, 'my-user-agent/1.0')
# create mirror_service (using the method from util.py from the quickstart(
mirror_service = create_service('mirror', 'v1', credentials)
Of course you would then also have to change the _insert_map_with_distance_from_home to use this mirror_service object, but moving this method away from your MainHandler would make more sense in this context anyway.

Related

read a direct message when arrival using telegram_api

i am working with an app and it needs to read direct messages from telegram when they arrive.
i searched on google but all i got was how to send a message not how to read brand new dms.
Thanks!
Telethon: Make sure you read the basics in the Docs to understand how to handle events.
I'm assuming you meant "mark as read", if not, read the docs, else read below:
in the event object you get to your callback, you have multiple unique convenience methods, and all the ones available on a Message object, one of them is event.mark_read()
to limit it only to send read requests to private chats; configure handler as needed, a minimal example:
#client.on(events.NewMessage(func=lambda e: e.is_private))
async def read_it_callback(event):
await event.mark_read()
you can also use client.send_read_acknowledge()

Wanting to chain web requests and pass data down through them in Twilio Studio

So I'm playing with Twilio Studio, and building a sample IVR. I have it doing a web request to an API that looks up the customer based on their phone number. That works, I can get/say their name to them.
I'm having trouble with the next step, I want to do another http request and pass the 'customer_id' that I get in webrequest1 to webrequest2, but it almost looks like all the web requests fire right when the call starts instead of in order/serialized.
It looks sorta like this;
call comes in, make http request to lookup customer (i get their customer_id and name)
split on content, if customer name is present, (it is, it goes down this decision path)
do another http request to "get_open_invoice_count", this request needs the customer_id though and not their phone number.
From looking at the logs it's always got a blank value there, even though in the "Say" step just above I can say their customer_id and name.
I can almost imagine someone is going to say I should go use a function, but for some reason I can't get a simple function to do a (got) get request.
I've tried to copy/paste this into a function and I kind of think this example is incomplete: https://support.twilio.com/hc/en-us/articles/115007737928-Getting-Started-with-Twilio-Functions-Beta-
var got = require('got');
got('https://swapi.co/api/people/?search=r2', {json: true})
.then(function(response) {
console.log(response)
twiml.message(response.body.results[0].url)
callback(null, twiml);
})
.catch(function(error) {
callback(error)
})
If this is the right way to do it, I'd love to see one of these ^ examples that returns json that can be used in the rest of the flow. Am I missing something about the execution model? I'm hoping it executes step by step as people flow through the studio, but I'm wondering if it executes the whole thing at boot?
Maybe another way to ask this question is; If I wanted to have the IVR be like
- If I know who you are, i send you down this path, if I know who you are I want to lookup some account details and say them to you and give you difference choices than if you are a stranger.
---- how do you do this?
You're right -- that code excerpt from the docs is just a portion that demonstrates how you might use the got package.
That same usage in context of the complete Twilio Serverless Function could look something like this:
exports.handler = function(context, event, callback) {
var twiml = new Twilio.twiml.MessagingResponse();
var got = require('got');
got('https://example.com/api/people/?search=r2', { json: true })
.then(function(response) {
console.log(response);
twiml.message(response.body.results[0].url);
callback(null, twiml);
})
.catch(function(error) {
callback(error);
});
};
However, another part of the issue here is that the advice in this documentation is perfectly reasonable for Functions when building an app on the Twilio Runtime, but there are a couple of unsaid caveats when invoking these functions from a Studio Flow context. Here's some relevant docs about that: https://support.twilio.com/hc/en-us/articles/360019580493-Using-Twilio-Functions-to-Enhance-Studio-Voice-Calls-with-Custom-TwiML
This function would be acceptable if you were calling it directly from an inbound number, but when you use the Function widget within a Studio flow to return TwiML, Studio releases control of the call.
If you want to call external logic that returns TwiML from a flow, and want to return to that flow later, you need to use the TwiML Redirect widget (see "Returning control to Studio" for details).
However, you don't have to return TwiML to Studio when calling external logic! It sounds like you want to make an external call to get some information, and then have your Flow direct the call down one path or another, based on that information. When using a Runtime Function, just have the function return an object instead of twiml, and then you can access that object's properties within your flow as liquid variables, like {{widgets.MY_WIDGET_NAME.parsed.PROPERTY_NAME}}. See the docs for the Run Function widget for more info. You would then use a "Split Based On..." widget following the function in your flow to direct the call down the desired branch.
The one other thing to mention here is the Make HTTP Request widget. If your Runtime Function is just wrapping a call to another web service, you might be able to get away with just using the widget to call that service directly. This works best when the service is under your control, since then you can ensure that the returned data is in a format that is usable to the widget.

Chaining Handlers with MediatR

We are using MediatR to implement a "Pipeline" for our dotnet core WebAPI backend, trying to follow the CQRS principle.
I can't decide if I should try to implement a IPipelineBehavior chain, or if it is better to construct a new Request and call MediatR.Send from within my Handler method (for the request).
The scenario is essentially this:
User requests an action to be executed, i.e. Delete something
We have to check if that something is being used by someone else
We have to mark that something as deleted in the database
We have to actually delete the files from the file system.
Option 1 is what we have now: A DeleteRequest which is handled by one class, wherein the Handler checks if it is being used, marks it as deleted, and then sends a new TaskStartRequest with the parameters to Delete.
Option 2 is what I'm considering: A DeleteRequest which implements the marker interfaces IRequireCheck, IStartTask, with a pipeline which runs:
IPipelineBehavior<IRequireCheck> first to check if the something is being used,
IPipelineBehavior<DeleteRequest> to mark the something as deleted in database and
IPipelineBehavior<IStartTask> to start the Task.
I haven't fully figured out what Option 2 would look like, but this is the general idea.
I guess I'm mainly wondering if it is code smell to call MediatR.Send(TRequest2) within a Handler for a TRequest1.
If those are the options you're set on going with - I say Option 2. Sending requests from inside existing Mediatr handlers can be seen as a code smell. You're hiding side effects and breaking the Single Responsibility Principle. You're also coupling your requests together and you should try to avoid situations where you can't send one type of request before another.
However, I think there might be an alternative. If a delete request can't happen without the validation and marking beforehand you may be able to leverage a preprocessor (example here) for your TaskStartRequest. That way you can have a single request that does everything you need. This even mirrors your pipeline example by simply leveraging the existing Mediatr patterns.
Is there any need to break the tasks into multiple Handlers? Maybe I am missing the point in mediatr. Wouldn't this suffice?
public async Task<Result<IFailure,ISuccess>> Handle(DeleteRequest request)
{
var thing = await this.repo.GetById(request.Id);
if (thing.IsBeignUsed())
{
return Failure.BeignUsed();
}
var deleted = await this.repo.Delete(request.Id);
return deleted ? new Success(request.Id) : Failure.DbError();
}

Force iron-router to get back an ready from waitOn

Currently it seems not to be possible to force a ready() state in the route. For example:
I have a waitOn on 2 subscribtions. One of them returns a Meteor.Error - now the route will be in the loading-state with no ending.
Is there a recommend way to tell iron-router "waitOn until subscribtion is ready OR subscribtion fails with an error" ?
Edit:
To explain my special case:
The waitOn is for a route which is for searching. The search arguments are "what" and "where". In "where" I have a plan String Address and need to convert it to a geo coordinate. For this I use the googlemaps converter on the Serverside (because its Sync). When no address was found I need to get back a error a lá "This address must be wrong". For this I need the functionality to get back an error.
When I do it like David Weldon said I need to do this step in the waitOn method but the Client-Side googlemaps converter is not Sync - instead its async so this would not work.
General Recommendations
It's okay for your publishers to throw errors, but those conditions should only be hit if the client does the wrong thing. In other words, you are solving the wrong problem - you should only subscribe when you know the publisher will not throw an error. Let's look at an example:
Suppose your route needs to subscribe to newPosts and postsForSuperuser. Assume that the postsForSuperuser publisher will throw an error if the user isn't a superuser. It's now the client's job not to let that happen. The waiton definition could look like:
waitOn: function() {
var subs = [Meteor.subscribe('newPosts')];
if (Roles.userIsInRole(Meteor.user(), ['superuser']))
subs.push(Meteor.subscribe('postsForSuperuser'));
return subs;
}
Because we are conditionally adding the postsForSuperuser subscription, we don't give the publisher the opportunity to throw an error.
Your specific use case
You case is a little more tricky, because mechanically the client is doing the correct thing but the user input may happen to be bad. In this case, I don't think throwing an error is appropriate. Here are some recommendations:
Avoid the problem by checking the address via a method call prior to changing the route.
If an address is found to be invalid, have the publish function immediately return this.ready(). This will prevent your route from failing, but you'll be left assuming that the reason you have no data is because of the address. If that's a valid assumption (i.e. it's the only possible reason for failure), then your router could deal with this by using a dataNotFound hook.
If you need to explicitly identify the cause of the error, have a close look at the 'counts' example from the docs. You can declare a client-only collection called addressErrors and then call this.added with a dynamically created document describing the cause of the error. The implementation of this is a little more tricky, and probably worthy of a separate question if you get stuck. I'd see if the first two make sense before attempting it.

Writing Per-Handler Middleware

I'm looking to pull some repetitive logic out of my handlers and put it into some per-handler middleware: specifically things like CSRF checks, checking for an existing session value (i.e. for auth, or for preview pages), etc.
I've read a few articles on this, but many examples focus on a per-server middleware (wrapping http.Handler): I have a smaller set of handlers that need the middleware. Most of my other pages do not, and therefore if I can avoid checking sessions/etc. for those requests the better.
My middleware, so far, typically looks something like this:
func checkCSRF(h http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
// get the session, check/validate/create the token based on HTTP method, etc.
// return HTTP 403 on a failed check
// else invoke the wrapped handler h(w, r)
}
}
However, in many cases I want to pass a variable to the wrapped handler: a generated CSRF token to pass to the template, or a struct that contains form data—one piece of middleware checks the session for the presence of some saved form data before the user hits a /preview/ URL, else it redirects them away (since they have nothing to preview!).
I'd like to pass that struct along to the wrapped handler to save having to duplicate the session.Get/type assertion/error checking logic I just wrote in the middleware.
I could write something like:
type CSRFHandlerFunc func(w http.ResponseWriter, r *http.Request, t string)
... and then write the middleware like so:
func csrfCheck(h CSRFHandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
// get the session, check/validate/create the/a token based on HTTP method, etc.
// return HTTP 403 on a failed check
// else invoke the wrapped handler and pass the token h(w, r, token)
}
... but that raises a few questions:
Is this a sensible way to implement per-handler middleware and pass per-request variables?
Prior to testing this (don't have access to my dev machine!), if I need to wrap a handler with multiple pieces of middleware, I assume I can just r.HandleFunc("/path/preview/", checkCSRF(checkExisting(previewHandler)))? The issue I'm seeing here is that the middleware is now tightly coupled: the wrapped middleware now needs to receive and then pass on the variable from the outer middleware. This makes extending http.HandlerFunc trickier/more convoluted.
Would gorilla/context fit better here and allow me to avoid writing 2-3 custom handler types (or a generic handler type) — and if so, how would I make use of it? Or could I implement my own "context" map (and run into issues with concurrent access?).
Where possible I'm trying to avoid falling for the "don't get caught writing a library" trap, but middleware is something that I'm likely to add/build on later in the project's life, and I'd like to "get it right" the first time around.
Some guidance on this would be much appreciated. Go's been great so far for writing a web application, but there's not a ton of examples around at this stage in its life and I'm therefore leaning on SO a little.
If I understood your question correctly, you're looking for a convenient way to pass additional parameters to your middleware, right?
Now, it's important to define what those parameters are. They could be some configuration values for your middleware – those can be set when the Handler type is being constructed). Instead of NewMyMiddleware(MyHandler), you do NewMyMiddleware(MyHandler, "parameter"), no problem here.
But in your case it seems like you want to pass per-request parameters, like a CSRF token. Passing those into the handler function would modify its signature and it would deviate from the standard Handler[Func] interface. You're right about middleware being more tightly coupled in this case.
You kind of mentioned the solution yourself – a context map is, in my opinion, a viable tool for this. It's not that hard to write one yourself – you basically need a map[*http.Request]interface{} and an RWMutex for safe concurrent access. Still, simply using gorilla/context should suffice – it seems like a (relatively) mature, well-written package with a nice API.
Shameless plug: if you're dealing with CSRF checks, why not try out my nosurf package?

Resources