logo
Tags down

shadow

How to do async api requests in a GAE application?


By : Diego Garcia
Date : October 16 2020, 08:10 AM
around this issue Urlfetch, which is bundled by default with GAE has a way of making asynchronous calls:
code :
from google.appengine.api import urlfetch

def post(self, *v, **kv):
  rpcs = []
  for url in urls:
    rpc = urlfetch.create_rpc()
    urlfetch.make_fetch_call(rpc, url)
    rpcs.append(rpc)

  results = [rpc.get_result() for rpc in rpcs]
  # do stuff with results


Share : facebook icon twitter icon

How would you time out multiple async requests with Scala's async?


By : allen
Date : March 29 2020, 07:55 AM
Does that help Here's a sketch of how it could be done (untested; I make no claim that this is the best solution):
code :
// I assume that the Web/Image/Video functions return instances of Future[Result]
val f1 = Web(query)
val f2 = Image(query)
val f3 = Video(query)
val t = timeout(80.milliseconds)

// using Scala's Future API
val results: Future[Seq[Result]] = for {
  r1 <- or(f1)(t)
  r2 <- or(f2)(t)
  r3 <- or(f3)(t)
} yield (r1.toSeq ++ r2.toSeq ++ r3.toSeq)

// OR using async
val results: Future[Seq[Result]] = async {
  val r1 = or(f1)(t)
  val r2 = or(f2)(t)
  val r3 = or(f3)(t)
  await(r1).toSeq ++ await(r2).toSeq ++ await(r3).toSeq
}

// or and timeout are utility/library functions defined below

def or[T](f1: Future[T])(f2: Future[Option[Nothing]]): Future[Option[T]] =
  Future.firstCompletedOf(f1 map Some.apply, f2)

// create a future that will complete successfully with None
// after the given duration passes
def timeout(d: Duration): Future[Option[Nothing]] = {
  val p = Promise[Option[Nothing]]
  Scheduler.after(d) { p success None }
  p.future
}

How to store return data from multiple async requests using HttpClient() until all requests complete?


By : Xero Cake
Date : March 29 2020, 07:55 AM
I wish this helpful for you I need to iterate through a series of post requests for data from a url. The requests need to be async. What is the best way to check all returns have completed, and to store that data until all data returned? Prefer to use HttpClient() , Well, first, bear in mind that you've got an async problem here:
code :
 HttpContent httpContent = new FormUrlEncodedContent(postData);           

 // whoops! .Result makes this line synchronous.
 HttpResponseMessage response =  client.PostAsync("/mydata", httpContent).Result;

 var responsecode = (int)response.StatusCode; 

 if (response.IsSuccessStatusCode)
 {
     var responseBodyAsText = await response.Content.ReadAsStringAsync();
     return responseBodyAsText;
 }
 else
 {
     return responsecode +" " +response.ReasonPhrase; 
 }
public async Task<string> ReadResultAsync(Task<HttpResponseMessage> responseTask)
{
    var response = await responseTask;

    var responsecode = (int)response.StatusCode; 

    if (response.IsSuccessStatusCode)
    {
        var responseBodyAsText = await response.Content.ReadAsStringAsync();

        return responseBodyAsText;
    }
    else
    {
        return responsecode + " " + response.ReasonPhrase; 
    }
}
// bear in mind, this code doesn't (necessarily) need to be in a
//  method marked "async". If you want to await on resultsTask, though,
//  it would need to be in an async method.

var tasks = myData
    .Select(x => new FormUrlEncodedContent(x)) //  IEnumerable<FormUrlEncodedContent>
    .Select(x => client.PostAsync("/mydata", x)) // IEnumerable<Task<HttpResponseMessage>>
    .Select(x => ReadResultAsync(x)) // IEnumerable<Task<string>>
    .ToArray(); // Task<string>[]

var resultsTask = Task.WhenAll(tasks); // here is Task<string[]>

Configuring OSGI Enroute REST application to allow async requests


By : Eigen
Date : March 29 2020, 07:55 AM
should help you out Sigh... found the answer while having difficulties getting an @WebServlet to start up and kept coming back to Whiteboard. A search for 'whiteboard async Java' brought up the HttpWhiteboardConstants setting: HttpWhiteboardConstants.HTTP_WHITEBOARD_SERVLET_ASYNC_SUPPORTED:
code :
@Component(..., property={...,
     HttpWhiteboardConstants.HTTP_WHITEBOARD_SERVLET_ASYNC_SUPPORTED+"=true", ...}...)
@RequireHttpImplementation
@Component(name="sse", property={
    HttpWhiteboardConstants.HTTP_WHITEBOARD_SERVLET_PATTERN+"=/sse/*",
    HttpWhiteboardConstants.HTTP_WHITEBOARD_FILTER_ASYNC_SUPPORTED+"=true",
    HttpWhiteboardConstants.HTTP_WHITEBOARD_SERVLET_ASYNC_SUPPORTED+"=true"},
    service=Servlet.class)
public final class ServerSideEventServlet extends HttpServlet
{
   @Override
   protected void doGet(HttpServletRequest request, HttpServletResponse response) 
       throws ServletException, IOException
   {
   }
}

Wait for async ajax requests to finish although both async true


By : Yannic Van Hoeymisse
Date : March 29 2020, 07:55 AM
fixed the issue. Will look into that further Assuming you're using a recent enough version of jQuery (>= 1.5), the solution as mentioned in the jQuery documentation would be:
code :
$.when( 
  $.ajax( "/page1.php" ), 
  $.ajax( "/page2.php" ) 
).then( myFunc, myFailure );

Loop through async requests with nested async requests


By : Alexander.Haliy
Date : March 29 2020, 07:55 AM
it should still fix some issue If this is all meant to be serial, then you can just use a for-of loop:
code :
export const importData = async() {
    const pSize = 15;
    const response = await getItems(pSize, 1);
    const noPage = Math.ceil(response.totalMerchandiseCount/pSize);

    for (let i = 1; i < noPage; i++) { // Are you sure this shouldn't be <=?
        const items = [];
        const data = await getItems(pSize, i);

        for (const {id, type} of data.merchandiseList) {
            const imageURL = await getImageURL(id, type);
            items.push({id, imageURL});
        }
        await api.mockable('sync', items);
    }
}
export const importData = async() {
    const pSize = 15;
    const response = await getItems(pSize, 1);
    const noPage = Math.ceil(response.totalMerchandiseCount/pSize);

    for (let i = 1; i < noPage; i++) { // Are you sure this shouldn't be <=?
        const data = await getItems(pSize, i);
        const items = await Promise.all(data.merchandiseList.map(async ({id, type}) => {
            const imageURL = await getImageURL(id, type);
            return {id, imageURL};
        }));
        await api.mockable('sync', items);
    }
}
export const importData = async() {
    const pSize = 15;
    const response = await getItems(pSize, 1);
    const noPage = Math.ceil(response.totalMerchandiseCount/pSize);

    for (let i = 1; i < noPage; i++) {
        const data = await getItems(pSize, i);
        const items = await Promise.all(data.merchandiseList.map(({id, type}) =>
            getImageURL(id, type).then(imageURL => ({id, imageURL}))
        ));
        await api.mockable('sync', items);
    }
}
Related Posts Related Posts :
  • Get mongod rs.status() results from a python script
  • ImportError: C extension: No module named 'parsing' not built
  • python pandas update column values related to previous updated row during iteration over it
  • 3 nested loops: Optimizing a simple simulation for speed
  • Assign subset of values to pandas dataframe with MultiIndex
  • How to group two sets of buttons on each top corner of the screen using Tkinter?
  • django login using class based for custom user
  • MRJob sort reducer output
  • Python Pandas Counts using rolling time window
  • Getting or editing a string from a column in a csv file with pandas
  • Python - Delete row in matrix/array if row contains
  • Using dicom Images with OpenCV in Python
  • Odoo ghost record
  • Creating and assigning multiple variables in a tkinter application
  • Graph dictionary
  • No changes to original dataframe after applying loop
  • AUC of Random forest model is lower after tuning parameters using hypergrid search and CV with 10 folds
  • Python: Reading multiple CSV files, and assigning each to a different variable
  • How to identify empty rectangle using OpenCV
  • How to iterate multilevel dataframe in python
  • How to limit the contour plot with a line plot?
  • Why subclassing a str or int behaves differently from subclising a list or dict?
  • Python decode with translation table
  • i need to click unordered links in the below URL using selenium, python
  • How to join pandas dataframe with itself?
  • How to apply a color cast to a video frame in OpenCV Python?
  • Is there any existing library for median filtering with kernel size greater then 5 using OpenCL acceleration in python?
  • Changing the color of points in scatter plot for different dummy values
  • Calculate center for each polygon in a list efficiently
  • Loading modules in the same Python package
  • replacing pixels in an imagewith pixels from another image python
  • Suggestion on picking the best options of two lists (minimum and maximum )python
  • Resetting Index in a Dataframe drops the Indexed column by 1 row
  • Convert number which are str from readlines to digits - python
  • Unable to authenitcate with python minds api
  • Print variables from a query in python
  • Ipython does not see the installed library
  • Javascript-like array-method chaining in Python?
  • PyQT: Get contents CustFormWidgetIem inside QListWidgetItem
  • Bottle server: HTTPResponse vs bottle.response
  • pytorch vgg model test on one image
  • Runtime scope and `main` symbol is different inside or outside a function
  • Use anaconda in pycharm (Import libraries error, updating anaconda and virtual environment)
  • how to get the sum of a CSV column list to print
  • Python plot drop lines with repeating value in column
  • receive binary file from POST request with BaseHTTPRequestHandler
  • D-Bus - 'ServiceUnknown' exception encountered while calling a remote procedure
  • Pandas .min() method doesn't seem fastest
  • Pandas: How to reference columns of structure: ('Name', n) ('Name', n+1)
  • Read a text file and remove all characters except alphabets & spaces in Python
  • Compute all powerset intersections of two lists
  • Applying literal_eval on string of lists of POS tags gives ValueError
  • Modelling a logic puzzle
  • What is the meaning of Copy_X in sklearn linear models
  • selenium.common.exceptions.ElementNotInteractableException: Message: Element is not displayed
  • pydev debugger does not stop in breakpoint
  • Python windows path regex
  • Flask and selenium-hub are not communicating when dockerised
  • How to use groupby on a single column and perform comparisons for multiple columns in Pandas?
  • Locate a python script without absolute path
  • shadow
    Privacy Policy - Terms - Contact Us © voile276.org