How to show data from other function into flask app - python

I am new to python and flask. Can anyone help me on this
from flask import Flask
import logging
logging.basicConfig(filename="err.log",level=logging.DEBUG)
student = ['abcd', '001', '11'] # I want to extract list value from here and needs to display in flask app
app = Flask(__name__)
#app.route("/")
def student_details():
print("student: "+student[0])
print("id: "+student[1])
print("grade: "+student[2])
student_details()
if __name__ == "__main__":
app.run(host='127.0.0.1', port="8000",debug=False)
Current Output: Internal Server Error
Desired Output:
student: abcd
id: 001
grade: 11

Although I would suggest reading about how to make html pages and use Jinja templates with flask, Use return instead of print. print() is used for printing on the console. You can also use a for loop to generate a string and then return it.
from flask import Flask
import logging
logging.basicConfig(filename="err.log",level=logging.DEBUG)
student = ['abcd', '001', '11'] # I want to extract list value from here and needs to display in flask app
app = Flask(__name__)
#app.route("/")
def student_details():
return "student " + str(student[0]) + " id " + str(student[1]) + " grade " + str(student[2])
if __name__ == "__main__":
app.run(host='127.0.0.1', port="8000",debug=False)

Related

can not read from specific mongo db in chatterbot always questions are writtne to chatterbot_database

I have a written a chatterbot integration code with flask , it was working well !! now whenever i try to train the chatbot its not dumping the data in the specified database , and if i try to ask a question , its reading and writing to chatterbot_database , even thought i specified in the code that i want him to use another database , im sharing my code , help please with explanation why this happened ?
#! /usr/bin/python3
from flask import Flask, render_template, request
from chatterbot import ChatBot
from chatterbot.response_selection import get_random_response
import random
import csv
import os
from botConfig import myBotName, chatBG, botAvatar, useGoogle, confidenceLevel
##Experimental Date Time
from dateTime import getTime, getDate
import logging
logging.basicConfig(level=logging.INFO)
application = Flask(__name__)
chatbotName = myBotName
print("Bot Name set to: " + chatbotName)
print("Background is " + chatBG)
print("Avatar is " + botAvatar)
print("Confidence level set to " + str(confidenceLevel))
#Create Log file
try:
file = open('BotLog.csv', 'r')
except IOError:
file = open('BotLog.csv', 'w')
bot = ChatBot(
"ChatBot",
logic_adapters=[
{
'import_path': 'chatterbot.logic.BestMatch'
},
{
'import_path': 'chatterbot.logic.LowConfidenceAdapter',
'threshold': confidenceLevel,
'default_response': 'IDKresponse'
}
],
response_selection_method=get_random_response,
#storage_adapter="chatterbot.storage.MongoDatabaseAdapter",
#database='ora_database',
#database_uri='127.0.0.1:27017'
database_uri='mongodb://localhost:27017/ora_database'
)
bot.read_only=True #Comment this out if you want the bot to learn based on experience
print("Bot Learn Read Only:" + str(bot.read_only))
#You can comment these out for production later since you won't be training everytime:
#bot.set_trainer(ChatterBotCorpusTrainer)
#bot.train("data/trainingdata.yml")
def tryGoogle(myQuery):
#print("<br>Try this from my friend Google: <a target='_blank' href='" + j + "'>" + query + "</a>")
return "<br><br>please use this link for more info <a target='_blank' href='http://www.google.com/'>" + myQuery + "</a>"
#application.route("/")
def home():
return render_template("index.html", botName = chatbotName, chatBG = chatBG, botAvatar = botAvatar)
#application.route("/get")
def get_bot_response():
userText = request.args.get('msg')
botReply = str(bot.get_response(userText))
if botReply is "IDKresponse":
botReply = str(bot.get_response('IDKnull')) ##Send the i don't know code back to the DB
if useGoogle == "yes":
botReply = botReply + tryGoogle(userText)
elif botReply == "getTIME":
botReply = getTime()
print(getTime())
elif botReply == "getDATE":
botReply = getDate()
print(getDate())
##Log to CSV file
print("Logging to CSV file now")
with open('BotLog.csv', 'a', newline='') as logFile:
newFileWriter = csv.writer(logFile)
newFileWriter.writerow([userText, botReply])
logFile.close()
return botReply
if __name__ == "__main__":
#application.run()
application.run(host='127.0.0.1', port=5000)

error list indices must be integers or slices, not str in flask

when I want to check the answers of a random question, flask debugger shows the error: list indices must be integers or slices, not str
my code:
from flask import Flask, render_template, flash, request, redirect, url_for
import random
app = Flask(__name__)
data = [{'q':'question text 1', 'ans':'a1', 'idsh':101}, {'q':'question text 2', 'ans':'a2', 'idsh':102}, {'q':'question text 3', 'ans':'a3', 'idsh':103}, {'q':'question text 4', 'ans':'a4', 'idsh':104}, ]
#app.route("/")
def home():
return render_template('index.html', data = random.choice(data))
#app.route('/anss')
def answerd():
if request.args.get('ans') == data['ans']:
return "yes"
else:
return "no"
if __name__ == '__main__':
app.run()
data = [{'q':'question text 1', 'ans':'a1', 'idsh':101}, ...]
creates a list. Lists can only be accessed by their indices. You have created a list that contains dictionaries. So, data[0] would point to {'q':'question text 1', 'ans':'a1', 'idsh':101}. You could get the answer with data[0]['ans'].
The route answerd() does not know for what question it should validate the answer.
You can either loop through all the dicts within your list and check if data[i]['idsh'] == request.args.get('idsh') or you need to store your data differently, for example like this (assuming idsh is the unique question id):
data = {101: 'a1', ...}
Then you can check for the correct answer like this:
if request.args.get('ans') == data[request.args.get('idsh')]:
Note that you should check if the arguments are valid before using them like this.

how to read information about ontology using owlready2

I am working in flask app and want to load ontology and print how many classes and how many individuals in this ontology
here is my code, it does not work
import flask
from owlready2 import *
app = flask.Flask(__name__)
app.config["DEBUG"] = True
#app.route('/', methods=['GET'])
def start():
onto_path.append("pizza.owl")
onto = get_ontology("pizza.owl")
onto.load()
print(onto.classes())
print(list(onto.individuals()))
html = ''
html += '<h2>clases: ' + onto.classes() + '</br>'
html += '<h3>individuals: ' + onto.individuals()
return html
#return "<h1>Distant Reading Archive</h1><p>This site is a prototype API for distant reading of science fiction novels.</p>"
app.run()
The method classes() and individuals() returns a generator, so you should cast the generator into a list, and ask for the length of that object.
n_classes = len(list(onto.classes()))
n_individuals = len(list(onto.individuals()))
After that, you should have the numbers on your variables and you can concatenate them with your HTML.

Flask server could not handle non ascii characters

I have wrriten a simple application using flask. Its main objective is to implement CLD2 (language detector) using post and get methods. It is working well for English but for any other language such Urdu, Arabic. It gives invalid results
Following is the corresponding script
# http://127.0.0.1:5000/cld2?text="Your input text string"
# OUTPUT ( It gives output as we done in CC)
#"585&URDU-99-1155"
from flask import Flask,abort,jsonify,request
from flask_restful import Resource, Api, reqparse
import cld2
from bs4 import BeautiflSoup
import sys
import urllib2, urllib
import re
reload(sys)
sys.setdefaultencoding('utf8')
app = Flask(__name__)
api = Api(app)
class HelloWorld(Resource):
def cld2_states(self, txt):
txt = txt.encode("utf8")
isReliable, textBytesFound, details = cld2.detect(txt)
outstr = str(textBytesFound)
for item in details: # Iterate 3 languages
if item[0] != "Unknown":
outstr += '&' + item[0] + '-' + str(item[2]) + '-' + str(int(item[3]))
return outstr
def get(self):
parser = reqparse.RequestParser()
parser.add_argument('text', type=str)
parser.add_argument('url', type=str)
_dict = dict(parser.parse_args())
if _dict["text"] is not None:
value = _dict["text"]
print type(value)
return self.cld2_states(value)
return None
def post(self):
data = request.get_json(force=True)
# print data
predict_request = [data['content']][1]
out = self.cld2_states(predict_request)
return jsonify(score=out)
api.add_resource(HelloWorld, '/cld2')
if __name__ == '__main__':
app.run(debug=True, port=6161, host='0.0.0.0')
If I give a query via get method, it give correct results but for same query in post method, it return just a number. But if text is in English then post also give correct result.
My client is a simple Java application then iterate over files and find their language one by one.
The problem might be with this line:
outstr = str(textBytesFound)
Instead of using str to convert from bytes to str, use str.decode(), like this:
outstr = textBytesFound.decode("utf-8")
(obviously if your text is not encoded with UTF-8, you need to tell Python the correct encoding to use)

Python Flask Only Run Code Once

I am trying to set a global variable as in:
# -*- coding: utf8 -*-
from flask import Flask, render_template,redirect,flash, url_for, session, request
from sqlalchemy.sql import text
from sqlalchemy.orm import aliased, Query
from sqlalchemy import exc
from flask_bootstrap import Bootstrap
from .forms import *
import zlib
#from sqlalchemy.orm.query import limit, order_by
from dbmodel import *
app = Flask(__name__)
app.secret_key = 'A0Zr98j/3yX R~XHH!jmN]LWX/,?RT'
Bootstrap(app)
MAX_ITEMS=50
MAX_ZIPS=5
MAX_ORDERS=20
clientMaxSQL="SELECT * FROM CLIENT WHERE 1"
engine, dbsession = dbconnect()
#app.route("/clientRegister",methods=['GET', 'POST'])
def clientRegister():
form = ClientQuery()
global clientMaxSQL
flash('maxSql at start %s ' %(clientMaxSQL))
if form.reset.data == "True":
flash('RESET TABLE FILTERS')
clientMaxSQL="SELECT * FROM CLIENT WHERE 1"
sql = clientMaxSQL
if form.validate_on_submit():
if len(form.compareVal.data.strip()) > 0 and ( any(c.isalpha() for c in form.compareVal.data) or any(c.isdigit() for c in form.compareVal.data)):
sql = sql + " AND " + form.columnSelection.data + form.comparisonSelection.data + "'" +form.compareVal.data+"'"
start=int(request.args.get('start', '0'))
prev=start-MAX_ITEMS
nextStart = start + MAX_ITEMS
tmpSQL = clientMaxSQL
clientMaxSQL = sql
sql = sql + " LIMIT " + str(start)+","+str(nextStart)
try:
clients = engine.execute(sql)
maxStart=engine.execute(clientMaxSQL).rowcount
flash('Attempting Query: %s' %(sql))
except:
flash('Invalid Comparison of %s' %(form.compareVal.data))
sql = tmpSQL + " LIMIT " + str(start)+","+str(nextStart)
clientMaxSQL=tmpSQL
clients = engine.execute(sql)
maxStart=engine.execute(clientMaxSQL)
flash('maxSql at end %s ' %(clientMaxSQL))
return render_template("clientRegister.html",form=form,maxStart=maxStart,clients=clients,start=start, prev=prev,nextStart=nextStart)
I am getting some strange results. It seems as if this statement (declared above all of my function definitions) is executing every once in a while on its own. Is this possible? It is imperative to my web app that this only runs once otherwise I will lose the current state of my query.
Added all the code in the program that ever changes the variable. It is resetting on its own though.
use the, #app.before_first_request decorator with the function to make it run only once
As in:
#app.before_first_request
def function_to_run_only_once():
#your statement(s)
This should make sure that your said statements execute only once in the entire lifetime of your program

Categories

Resources