Python: How to print from flask to console - python

I am working on a facebook chatbot. I know there are some post for the similar question, but I cannot get it works.
Below is my code:
from __future__ import print_function
import sys
from flask import Flask, request, app
API_ROOT = '/webhook'
app = Flask(__name__)
def eprint(*args, **kwargs):
print(*args, file=sys.stderr, **kwargs)
#app.route(API_ROOT, methods=['POST'])
def fb_receive_message():
eprint('message received')
if __name__ == '__main__':
eprint('Hello world!')
app.run(host='XXX.XXX.XXX.XXX',debug=True,port=XXX)
Outcome:
Hello world!
* Restarting with stat
when I try with "post" then it does not print anything

Related

Flask is not providing a URL

I am a new programmer and I am trying to connect my bot to flask to create a URL for discord.
when I run it, it doesn't do it. Am I missing a line here because it is not coming up with an error but it will not run either.
from threading import Thread
app = Flask ('__code__')
#app.route('/')
def home():
return "Hello. I am alive!"
app.run(host='0.0.0.0',port=5000)
def keep_alive():
t = Thread(target=run)
t.start()
if __name__ == '__code__':
app.run()```
Can someone point me in the right direction? I normally work on python 3.
Thank you
Try running the app when checking the name of your code, not in home() function:
from flask import Flask
from threading import Thread
app = Flask ('__code__')
#app.route('/')
def home():
return "Hello. I am alive!"
def keep_alive():
t = Thread(target=run)
t.start()
if __name__ == '__code__':
app.run(host='0.0.0.0',port=5000)

Return continuous terminal log through flask client - Python

Is there a way to return multiple responses to 1 get request?
I have a basic flask app where I am trying to make it run another python app and send the terminal logs to the client side.
I can return a json value but I can't return any text or the output of the terminal.
Here is the server side:
from flask import Flask, stream_with_context, request, Response
from flask_restful import Api, Resource
from flask_socketio import SocketIO
import intermedia_choose_action_flask
import subprocess
app = Flask(__name__)
api = Api(app)
socketio = SocketIO(app)
class spamblacklistsend(Resource):
def get(self):
imapp = subprocess.Popen(["python3", "/home/tech/scripts/Intermedia_automate/intermedia_choose_action.py", "--addblockeveryone", "--ed", "test#fakeu.com"], bufsize=10, errors='replace')
imapp.app_context().push()
# p = subprocess.Popen(["python3", "/home/tech/scripts/Intermedia_automate/intermedia_choose_action.py", "--addblockeveryone", "--ed", "test#fakeu.com"], bufsize=10, errors='replace')
return imapp.app_context().push()
api.add_resource(spamblacklistsend, "/spamblacklistsend")
if __name__ == "__main__":
app.run(debug=True)
Here is the client side:
from flask import json
import requests
BASE = "http://127.0.0.1:5000/"
response = requests.get(BASE + "spamblacklistsend")
print(imapp.app_context().push())
I know that return stops the function. Is there anyway to return and continue?

Python POST api giving error. Logs not found

I am new with python. I have a POST api in python deployed on AWS using steps from the below mentioned link.
https://www.digitalocean.com/community/tutorials/how-to-serve-flask-applications-with-uwsgi-and-nginx-on-ubuntu-16-04
The api is giving internal server error and the logs are not getting printed. Is there a directory which I'm missing or can I print the logs somehow?
Also if someone can help with what could be the possible issue with the API :
#!/usr/bin/env python2.7
#!flask/bin/python
#!/usr/bin/python
import numpy
import sys,os
import codecs
import json
import phonetics
import transliteration
import jellyfish
import traceback
from pyjarowinkler import distance
from flask import Flask, jsonify, request
import panphon.distance
from datetime import datetime
from flask_cors import CORS
def obj_dict(obj):
return obj.__dict__
# logFile = open('log.txt','a')
app = Flask(__name__)
cors = CORS(app, resources={r"/todo/api/*": {"origins": "*"}})
#app.route('/todo/api/v1.0/tasks', methods=['GET''POST'])
def get_tasks():
if request.method == 'GET':
return "done with get request"
elif request.method == 'POST':
try :
content = request.get_json()
with codecs.open('words.txt', 'a') as file:
for line in content['words']:
file.write("\n"+line.encode('utf-8'))
except Exception:
with open('log.txt','a') as logger:
logger.write("At "+str(datetime.now())+" "+traceback.format_exc())
logger.write("\n\n")
return "done"
if __name__ == '__main__':
import logging
logging.basicConfig(filename='log.txt',level=logging.DEBUG)
app.run(host='0.0.0.0', debug = False)
NOTE: The other imports are for some other purpose. I need the POST API to work.
Try setting debug = True
For example
if __name__ == '__main__':
import logging
logging.basicConfig(filename='log.txt',level=logging.DEBUG)
app.run(host='0.0.0.0', debug = True)
Also you don't need to import logging as you can use flask's logger which should be accessible using app.logger
If this is production then debug=True is not recommended.
Flask considers ERROR as the default logging level if you do not set up log level
So you might try setting the log level using app.logger.setLevel(logging.DEBUG)
#app.route('/todo/api/v1.0/tasks', methods=['GET', 'POST'])
def get_tasks():
if request.method == 'GET':
return "done with get request"
elif request.method == 'POST':
try :
content = json.loads(request.get_data())
with codecs.open('words.txt', 'a') as file:
for line in content['words']:
file.write("\n"+line.encode('utf-8'))
except Exception:
with open('log.txt','a') as logger:
logger.write("At "+str(datetime.now())+" "+traceback.format_exc())
logger.write("\n\n")
return "done"

Flask hangs the main thread

I want to use the Flask as my RESTful API server, but the main thread hangs and it doesn't execute the code after the app.run().
In util/restAPI.py
from flask import Flask
app = Flask('__name__')
#app.route('/')
def index():
return "Hello, World!"
In main.py
from util import restAPI
if __name__ == "__main__":
restAPI.app.run()
print "haha"
Should I use threads or something else to help me?

How to log to socket in Flask

I have the rest of my program using a socketHandler to log which is being consumed using http://code.activestate.com/recipes/577025-loggingwebmonitor-a-central-logging-server-and-mon/.
How do I setup my flask app to log this?
I tried the following based on their docs (http://flask.pocoo.org/docs/errorhandling/#logging-to-a-file):
class HelloWorld(Resource):
def get(self):
resp = "HELLO!"
app.logger.info("GET HelloWorld %s", resp)
return resp
if __name__ == '__main__':
import logging
import logging.handlers # you NEED this line
socketHandler = logging.handlers.SocketHandler('localhost',
logging.handlers.DEFAULT_TCP_LOGGING_PORT)
socketHandler.setLevel(logging.INFO)
app.logger.addHandler(socketHandler)
app.run('0.0.0.0')

Categories