logo
down
shadow

Async await with sqs receive messages not working properly


Async await with sqs receive messages not working properly

By : user3042913
Date : November 29 2020, 12:01 PM
To fix this issue You are running poll_queue directly as a coroutine. Execute it with the ensure_future(), it will wrap up the coroutine in a Task object. Only Task objects can be awaited and suspended by the event loop.
code :
import aiobotocore
import json
import logging
import asyncio
from aiohttp import web
app = web.Application()

max_queue_messages = 10
AWS_REGION=
AWS_KEY=
AWS_SECRET=

queue_url =

async def poll_queue(client):
    while True:
        try:
            # This loop wont spin really fast as there is
            # essentially a sleep in the receieve_message call
            response = await client.receive_message(
                QueueUrl=queue_url,
                WaitTimeSeconds=2,
            )

            if 'Messages' in response:
                for msg in response['Messages']:
                    # print('Got msg "{0}"'.format(msg['Body']))
                    print('got queue message')
            else:
                print('No messages in queue')
        except KeyboardInterrupt:
            break

    print('Finished')
    await client.close()


def func1():
    loop = asyncio.get_event_loop()
    session = aiobotocore.get_session(loop=loop)
    client = session.create_client('sqs', region_name=AWS_REGION,
                               aws_access_key_id=AWS_KEY,
                               aws_secret_access_key=AWS_SECRET)
    asyncio.ensure_future(poll_queue(client))

async def hello(request):
    return web.Response(text="Hello, world")

def func2():
    app.add_routes([web.get('/', hello)])
    print("Starting web Server")
    web.run_app(app, host= "127.0.0.1",port= 5000)

if __name__ == "__main__":
    loop = asyncio.get_event_loop()
    asyncio.set_event_loop(loop)

    func1()
    func2()

    loop.run_forever()


Share : facebook icon twitter icon
Why won't my container component receive result of Async Await properly?

Why won't my container component receive result of Async Await properly?


By : Cristian Omar Cruz
Date : March 29 2020, 07:55 AM
I wish did fix the issue. to @FelixKling and @Think-Twice .
I did actually end up a) wrapping the util function in a Promise, and reading up on async await. Thought i understood that but there were some quirks i didnt.
code :
export function checkLoginStatus() {
    return new Promise((resolve, reject) => {
        const unsubscribe = firebase.auth().onAuthStateChanged(user => {
            unsubscribe(); // <--- calls itself and resolves with a successful user object or null
            resolve(user);
        }, reject('api has failed'));
    });
}
   isUserAlreadyAuthenticated = async () => {

        try {
            let user = await this.props.checkLoginStatus();
            console.log('react side: ', user);
            if (user && user.email) {
                this.setState({
                    isLoggedIn: true, // <-- when true page navs to Homepage
                });
            }
        } catch(err) {
            console.log('catch | api error: ', err);   
        }
    }
Async\Await with promise not working properly

Async\Await with promise not working properly


By : Daniel Green
Date : March 29 2020, 07:55 AM
fixed the issue. Will look into that further I have an Async function and I send to another Async function that wait for the promise to resolve, but for some reason its not waiting for the reslove. , In this line:
code :
 connection.connect((err)=>{res(err)});
 function makeQuery(connection, query) {
  return new Promise((resolve, reject) => {
    connection.connect(error => {
      if(error) return reject(error);
      connection.query(query, (error, results, fields) => {
        if(error) return reject(error);

        console.log(results);
        resolve(results);

        connection.close(); // actually you should open the connection to the db once ...
      });
    });
  });
}

const openTemplate = header =>
  makeQuery(connection, `SELECT * FROM streamingpages WHERE ID=${header.routerParamas.id}`); // MYSQL INJECTION POSSIBLE!!!!

Router.get("/openPage/:id",async(res,req)=>{
 var params = res.getHeaderParams();
 const result = await openTemplate(parms);
 res.returnJson(result, "Success");
});
why my async await is not working properly

why my async await is not working properly


By : michade
Date : March 29 2020, 07:55 AM
I wish this help you When you use await when invoking a function, you're basically waiting for a promise inside that function to resolve. The invoked function is intended to return that promise.
In your code, the login function does invoke connection.query, but there isn't any promise that waits for the query to resolve.
code :
const login = async function () {
  try {
    console.log('Login process started');
    const newToken = await jwt.sign({login:'login'},config['token-secret'],{ expiresIn: config['token-expires']});
    let username = 'root_admin'
    let password = 'Admin123';
    let token = String(cryptojs.lib.WordArray.random(20));
    console.log("token : "+token);

    return new Promise(function(resolve, reject){

      connection.query('SELECT * FROM users where username = ?  ',[username], async function(err, rows) { // await won't do anything here,
      // you should only use await with functions that return promises.
        if (err) {
          console.log("Looged out failed");
          throw new Error(err);
        } else {
          const user = rows[0];
          console.log("psdsdsd");
          if(bcrypt.compareSync(password,user.passwordHash)) {
            await connection.query('SELECT * FROM organizations where id = ?  ',[user.organizationId], async function(err, org_data) {
              if (err) {
                console.log("Looged out failed");
                throw new Error(err);
              } else {
                console.log("sdsd");
                //console.log(org_data);
                if(typeof org_data.name!='undefined') {
                  organization = org_data.name;
                } else {
                  organization = 'VeriCurious';
                }
                //console.log(organization);
                // create a token
                const token = await jwt.sign({ id: user.id, username: user.username, organizationId: user.organizationId, organization: organization}, config['token-secret'], {
                  expiresIn: config['token-expires'] // expires in 30 minutes
                }); 
                console.log("Successfull loggedin");
                console.log("New generated token : "+token);
                resolve(token); // this signals the Promise to resolve.
                // return token;
              }
            });
          }
        }    
      });
    });
  } catch (error) {
      console.log(error);
  }
}
const login = async function () {
  // skipped a lot of code and logic since this is an example
    const rows = await connection.query('SELECT * FROM users where username = ?  ',[username]);
    const user = rows[0];
    const org_data = await  connection.query('SELECT * FROM organizations where id = ?  ',[user.organizationId]);
    const organization = org_data.name;

    return await jwt.sign({ id: user.id, username: user.username, organizationId: user.organizationId, organization: organization}, config['token-secret'], {
                expiresIn: config['token-expires'] // expires in 30 minutes
  });
}
Async/await function isn't working properly

Async/await function isn't working properly


By : user3270607
Date : March 29 2020, 07:55 AM
I wish this help you Try await Promise.all(files.map(async _ => {...})), but keep in mind .all will reject on first failure.
how to use async await on javascript frontend to receive data from async await node.js backend

how to use async await on javascript frontend to receive data from async await node.js backend


By : user3719787
Date : March 29 2020, 07:55 AM
should help you out You don't can use return in express route. use instead res object like this: res.send(response.data.data)
see: https://expressjs.com/pt-br/api.html#res
Related Posts Related Posts :
  • Tuning the hyperparameter with gridsearch results in overfitting
  • some coordinates that I extracted from geocoder in Python are not saving in the variable I created
  • 7C in cs circles- python Im not sure what is wrong with this yet
  • How to fix 'AttributeError: 'list' object has no attribute 'shape'' error in python with Tensorflow / Keras when loading
  • python - thread`s target is a method of an object
  • Retrieve Variable From Class
  • What is the reason for matplotlib for printing labels multiple times?
  • Why would people use ThreadPoolExecutor instead of direct function call?
  • When clear_widgets is called, it doesnt remove screens in ScreenManager
  • Python can't import function
  • Pieces doesn't stack after one loop on my connect4
  • How to change font size of all .docx document with python-docx
  • How to store a word with # in .cfg file
  • How to append dictionaries to a dictionary?
  • How can I scrape text within paragraph tag with some other tags then within the paragraph text?
  • Custom entity ruler with SpaCy did not return a match
  • Logging with two handlers - one to file and one to stderr
  • How to do pivot_table in dask with aggfunc 'min'?
  • This for loop displays only the last entry of the student record
  • How to split a string by a specific pattern in number of characters?
  • Python 3: how to scrape research results from a website using CSFR?
  • Setting the scoring parameter of RandomizedSeachCV to r2
  • How to send alert or message from view.py to template?
  • How to add qml ScatterSeries to existing qml defined ChartView?
  • Django + tox: Apps aren't loaded yet
  • My css and images arent showing in django
  • Probability mass function sum 2 dice roll?
  • Cannot call ubuntu 'ulimit' from python subprocess without using shell option
  • Dataframe Timestamp Filter for new/repeating value
  • Problem with clicking select2 dropdownlist in selenium
  • pandas dataframe masks to write values into new column
  • How to click on item in navigation bar on top of page using selenium python?
  • Add multiple EntityRuler with spaCy (ValueError: 'entity_ruler' already exists in pipeline)
  • error when replacing missing ')' using negative look ahead regex in python
  • Is there a way to remove specific strings from indexes using a for loop?
  • select multiple tags by position in beautifulSoup
  • pytest: getting AttributeError: 'CaptureFixture' object has no attribute 'readouterror' capturing stdout
  • Shipping PyGObject/GTK+ app on Windows with MingW
  • Python script to deduplicate lines in multiple files
  • How to prevent window and widgets in a pyqt5 application from changing size when the visibility of one widget is altered
  • How to draw stacked bar plot from df.groupby('feature')['label'].value_counts()
  • Python subprocess doesn't work without sleep
  • How can I adjust 'the time' in python with module Re
  • Join original np array with resulting np array in a form of dictionary? multidimensional array? etc?
  • Forcing labels on histograms in each individual graph in a figure
  • For an infinite dataset, is the data used in each epoch the same?
  • Is there a more efficent way to extend a string?
  • Is it possible to do this loop in a one-liner?
  • invalid literal for int() with base 10: - django
  • Why does my code print a value that I have not assigned as yet?
  • the collatz func in automate boring stuff with python
  • How to find all possible combinations of parameters and funtions
  • about backpropagation deep neural network in tensorflow
  • Sort strings in pandas
  • How do access my flask app hosted in docker?
  • Replace the sentence include some text with Python regex
  • Counting the most common element in a 2D List in Python
  • logout a user from the system using a function in python
  • mp4 metadata not found but exists
  • Django: QuerySet with ExpressionWrapper
  • shadow
    Privacy Policy - Terms - Contact Us © festivalmusicasacra.org