I have built a SMS service (using Twilio) that the user texts to get realtime bus information. At the moment i have been hosting this on my personal computer using ngrok. Now i want to use AWS to host this service, but I am not sure as to how i should go about it. I have tried running a flask webserver and trying to get ngrok to run on AWS, but no luck.
Here is my code concerning Flask and Twilio's REST Api:
app = Flask(__name__)
#app.route("/sms", methods=['GET', 'POST'])
def hello_monkey():
resp = MessagingResponse()
response = request.form['Body']
if (" " in response):
response = response.split(" ")
result = look_up(response[0], response[1])
else:
result = look_up(response, False)
resp.message(result)
return str(resp)
if __name__ == "__main__":
app.run(debug=True)
There is a blog post on the Twilio blog on How to Send SMS Text Messages with AWS Lambda and Python 3.6. It does not use Flask, but it can definitely be modified to achieve your goal. Alternatively, you could read about using Flask with AWS Elastic Beanstalk here.
Running ngrok on AWS is not the correct approach to this. If you wanted to host your own Flask server, you could use something like Lightsail, but that's overkill for this usage.
Related
NOT : I only have rcon password
I want to retrieve the logs on the csgo server, but I couldn't do it.
I can use c# nodejs and python
I created a project in replit using python and flask and with logaddress_add_http.I added the link of this project to the csgo server and it worked, but I could not figure out how to get the logs by adding the ip of my own computer with the logaddress_add to the csgo server.
Please help me, I couldn't find any sources about this
log on
logaddress_add_http "https://CSGO.synx12.repl.co"
My Code:
from flask import Flask,request
app=Flask(__name__)
#app.route("/",methods=["GET","POST"])
def index():
if(request.method=="GET"):
return "GET"
elif(request.method=="POST"):
data=request.get_data()
print(data)
return f"Data : {data}"
if(__name__=="__main__"):
app.run(host="0.0.0.0",port=8080)
I'm sending a message to the server with rcon
And Result
here logaddress_add_http works fine but I couldn't get logaddress_add to work at all
I want your help for this.
I am trying to deploy a Python app in Google Cloud Run to perform some tasks automatically and these tasks require access to my BigQuery.
I have tested the implementation in localhost through Cloud Shell, and it worked just as expected. Then I created a Cloud Run Service and all functions that do not require access to BigQuery work normally, but when I they require, I get the following error:
google.auth.exceptions.DefaultCredentialsError: File /XXXXXX/gbq.json was not found.
However, the file is there (the folders are correct, and I also tested adding copies of the file in other folders):
Any suggestions to solve the problem or a workaround I could use?
Thanks in advance
ADDITIONAL INFO:
main.py function:
(the bottom part of the code is used to test the app in localhost, which works perfectly)
from flask import Flask, request
from test_py import test as t
app = Flask(__name__)
#app.get("/")
def hello():
"""Return a friendly HTTP greeting."""
chamado = request.args.get("chamado", default="test")
print(chamado)
if chamado == 'test':
dados = f'chamado = test?\n{chamado == "test"}\n{t.show_data(chamado)}'
elif chamado == 'bigqueer':
dados = f'chamado = test?\n{chamado == "test"}\n{t.show_bq_data()}'
else:
dados = f'chamado = test?\n{chamado == "test"}\n{t.show_not_data(chamado)}'
print(dados)
return dados
if __name__ == "__main__":
# Development only: run "python main.py" and open http://localhost:8080
# When deploying to Cloud Run, a production-grade WSGI HTTP server,
# such as Gunicorn, will serve the app.
app.run(host="localhost", port=8080, debug=True)
BigQuery class:
class GoogleBigQuery:
def __init__(self):
os.environ['GOOGLE_APPLICATION_CREDENTIALS'] = '/XXXXXX/gbq.json'
self.client = bq.Client()
def executar_query(self, query):
client_query = self.client.query(query)
result = client_query.result()
return result
Cloud Run deploy:
gcloud run deploy pythontest \
--source . \
--platform managed \
--region $REGION \
--allow-unauthenticated
YOU DO NOT NEED THAT
Excuse my first brutal words but it's extremely dangerous to do what you do. Let me explain.
In your container, you put, in plain text a secret. Keep in mind that your container is like a zip. There is nothing secret, encrypted in it. You can convince yourselves by using dive and exploring your container layers and data.
Therefore: DO NOT DO THAT!
So now, what to do?
On Google Cloud, all the services can use the Metadata server to get credentials. The client libraries leverage it and you can rely on the default credential with you initialise your code. That mechanism is named ADC.
In your code, simpy remove that line: os.environ['GOOGLE_APPLICATION_CREDENTIALS'] = '/XXXXXX/gbq.json'
So that, when you deploy your Cloud Run service, specify the runtime service account that you want to use. That's all! The Google Cloud environment and libraries will do the rest
I built a simple flask server in order to automate python scripts based on an HTTP POST Request coming in from an outside service. This service sends these requests in response to events that we have created based on data conditions. All the flask server needs to do is parse the requests, and take the numerical value stored in the request and use it to run the corresponding python script. At one point, this system was working consistently. Fast forward a few months, the server was no longer working when tried again. No changes were made to the code. According to wireshark, The computer hosting the flask server is receiving the request to the correct port, but the request is now timing out. The host system is failing to respond to the request. Any Idea what is going on here? The firewall has temporarily been turned off.
Alternatively, is there another better package to achieve this goal with?
from flask import Flask, request
import threading
import runpy
app = Flask(__name__)
#app.route('/', methods=['POST'])
def PostHandler():
directory = {}
with open(r"M:\redacted") as f:
for line in f:
(key,val) = line.split()
directory[int(key)] = val
print(directory)
path = r"M:\redacted"
content = request.json
content = content['value']
print(content)
sel_script = int(content)
print(directory[sel_script])
runpy.run_path(path_name=path + directory[sel_script])
return
app.run(host="10.244.xx.xx", port=8080, threaded=True)
I am trying to create a RESTful app using Flask and swagger. But when I run the endpoint I do not see the methods documented in the browser like described here for example http://michal.karzynski.pl/blog/2016/06/19/building-beautiful-restful-apis-using-flask-swagger-ui-flask-restplus/
Instead just the 404 not found error. Here is my code:
def init_deserializer_restful_api():
# Get port number for the web app.
PORT = 8000
# Initiate the Flask app
app = Flask(__name__)
Swagger(app)
CORS(app)
# Handler for deserializer
#app.route("/deserialize", methods=['POST','GET'])
def handle_deserialization_request():
# Method description
# Method content
App is run like this:
app.run(port=PORT, host="0.0.0.0")
I run http://localhost:8000/deserializer I get The requested URL was not found on the server. If you entered the URL manually please check your spelling and try again.
Questions:
1. How do I feed flask the request.json it requires?
2. How do I get swagger to work?
try localhost:8000/apidocs/index.html
Explanation
This is the default endpoint of Swagger. What you were trying to do is accessing one endpoint of your API and expecting it to render the Swagger UI. Swagger UI is an ADDITIONAL endpoint to your API which lists and lets you try all other endpoints. Hope that helps!
How can I access Google App Engine endpoints API for Python (not web, android, ios)?
I read this tutorial but it not explains it enough to understand this.
As I found on serve side I can use such code to identify user:
#endpoints.method(message_types.VoidMessage, Greeting,
path='hellogreeting/authed', http_method='POST',
name='greetings.authed')
def greeting_authed(self, request):
current_user = endpoints.get_current_user()
email = (current_user.email() if current_user is not None
else 'Anonymous')
return Greeting(message='hello %s' % (email,))
Full code of API example
How can I connect from Python client to this API and call 'hellogreeting/authed' with authentication current_user != None.
Can you share some code how to do it?
app_id = 'xxx'
user = 'xxx'
password = 'xxx'
callAPI(app_id, user, password, 'hellogreeting/authed')
You need to configure your App Engine instance to be able to serve your API. I would recommend you create a separate module dedicated to your API, like explained in these docs: https://developers.google.com/appengine/docs/python/endpoints/api_server.
Once everything is correctly set up on the server side, you can call your API using something like: http://your-module.your-app.appspot.com/_ah/spi/hellogreeting/authed.
If you're using the development server, things are a little bit different for accessing modules, but once you know which port number the App Engine development server has assigned to your API module, you can reach it locally using: http://localost:<api_module_port_#>/_ah/spi/hellogreeting/authed.
Hope this helped.