PREFACE
Hello all I am getting a very strange error when I am trying to use the flask module for python... First let me explain that I first started writing the program and then it stopped working NO PROBLEM My last copy should work... Right? After I tried to revert back to 2 versions before the current versions code I was still getting the same error I have done everything I can think of doing now it is time to give it to the professionals
Ok so what is happening is that when I try to run my flask applications
Traceback (most recent call last):
File "/Users/me/Desktop/ASL server/router.py", line 47, in <module>
from flask import *
File "/Library/Python/2.7/site-packages/flask/__init__.py", line 17, in <module>
from werkzeug.exceptions import abort
File "/Library/Python/2.7/site-packages/Werkzeug-0.9.4-py2.7.egg/werkzeug/__init__.py", line 154, in <module>
__import__('werkzeug.exceptions')
File "/Library/Python/2.7/site-packages/Werkzeug-0.9.4-py2.7.egg/werkzeug/exceptions.py", line 71, in <module>
from werkzeug.wrappers import Response
File "/Library/Python/2.7/site-packages/Werkzeug-0.9.4-py2.7.egg/werkzeug/wrappers.py", line 26, in <module>
from werkzeug.http import HTTP_STATUS_CODES, \
File "/Library/Python/2.7/site-packages/Werkzeug-0.9.4-py2.7.egg/werkzeug/http.py", line 28, in <module>
from urllib.request import parse_http_list as _parse_list_header
ImportError: No module named request
Currently I have tried to uninstall the module and reinstall it along with all supporting modules. The code is a reverted code that was from before the error occourd and now the error is happening again (No changes have been made to the old code) I do not know what the problem is ...
My python code is
from flask import *
import flask
from flask import render_template
import os
import random
import sys
app = Flask(__name__)
app.secret_key ="REST SECRET"
##############################################
#app.errorhandler(503) #
def page_not_found(e): #
flash('503 Service Unavailable') #
return render_template('500.html'), 500 #
#app.errorhandler(408) #
def page_not_found(e): #
flash('408 Request Timeout') #
return render_template('403.html'), 408 #
#app.errorhandler(401) #
def page_not_found(e): #
flash('401- Restricted') #
return render_template('403.html'), 401 #
##############################################
def getip():
c = request.remote_addr
i = c.encode(encoding='UTF-8',errors='strict')
ip = i.encode(encoding='UTF-8',errors='strict')
#app.route('/')
def home():
ipa = getip()
session[ipa] = ipa
print session
print ipa
return render_template('index.html')
#app.route('/donate')
def donate():
return render_template('donate.html')
#app.route('/learn/fingerspell/end')
def learnfinger():
return render_template('Welcometofinger.html')
#app.route('/learn/fingerspell',methods=["GET","POST"])
def learnfingera():
x = "a"
if request.method == "POST":
if request.form['next'] == "clear":
return redirect('/learn/fingerspell/b')
return render_template("fingerspell.html",error=x)
#app.route('/learn/fingerspell/b',methods=["GET","POST"])
def learnfingerb():
x = "b"
if request.method == "POST":
if request.form['next'] == "clear":
return redirect('/learn/fingerspell/c')
return render_template("fingerspell.html",error=x)
# And so on and on till you get to Z
#app.route('/learn/fingerspell/z',methods=["GET","POST"])
def learnfingerz():
x = "z"
if request.method == "POST":
if request.form['next'] == "clear":
return redirect('/learn/fingerspell/end')
return render_template("fingerspell.html",error=x)
#app.route('/learn/basic-words')
def learnwordb():
return render_template('bwordsmain.html')
#app.route('/learn/basic-words/course')
def learnwordb_course():
flash("Welcome to your first lesson ")
return
#app.route('/learn/basic-words/course/test/id1',methods=["GET","POST"])
def test1baiscstart():
score = 0
if request.method == "POST":
if request.form['a'] == "ASL":
score += 1
return render_template('test1.html')
#app.route('/learn')
def learn():
return render_template('newopt.html')
#app.route('/test/id/1',methods=["POST","GET"])
def testabcs():
score = 100
missq = 0
truea = 5
if request.method == "POST":
ab = request.form['qa']
ba = request.form['qb']
ca = request.form['qc']
da = request.form['qd']
ea = request.form['qe']
a = str(ab).lower()
b = str(ba).lower()
c = str(ca).lower()
d = str(da).lower()
e = str(ea).lower()
if True:
if a != "asl is fun":
score -= 20
missq += 1
elif b != "this isnt hard":
score -= 20
missq += 1
elif c != "its fun":
score -= 20
missq += 1
elif d != "m":
score -= 20
missq += 1
elif e != "t":
score -= 20
missq += 1
else:
flash("DEATH ERROR")
flash("you scored "+ str(score)+"% and missed " + str(missq) + " out of " + str(truea))
return render_template('info.html')
return render_template("abcstest.html")
#app.route('/games')
def games():
return render_template("games.html")
if __name__ == '__main__':
port = int(os.environ.get('PORT', 5001))
app.debug = True
app.run(host='0.0.0.0',port=port)
Actually the 2 statements is doing nearly the same:
from flask import *
import flask
when you try to use a method in flask, you have 2 choices:
1st:
from flask import *
c = request.remote_addr
2nd:
import flask
c = flask.request.remote_addr
Do you notice the different?When using from a_module import *, you can just use the method name in the module.When using import a_module, you have to the compiler which module you use, such as: a_module.method_name
Sometimes directories break... Try copying the files out of the directory and make a new directory and then rerun the server that should work.
I figured this out because it worked before and then it worked again. Your code is just fine!
Related
Traceback (most recent call last):
File "C:\xampp\htdocs\Plag\scripts\main.py", line 8, in
from extractdocx import *
File "C:\xampp\htdocs\Plag\scripts\extractdocx.py", line 18, in
from docx import opendocx, getdocumenttext
File "C:\Users\zeesh\AppData\Local\Programs\Python\Python39\lib\site-packages\docx.py", line 30, in
from exceptions import PendingDeprecationWarning
ModuleNotFoundError: No module named 'exceptions'
# -*- coding: utf-8 -*-
# Master script for the plagiarism-checker
# Coded by: Shashank S Rao
#import other modules
from cosineSim import *
from htmlstrip import *
from extractdocx import *
#import required modules
import codecs
import traceback
import sys
import operator
import urllib.request, urllib.parse, urllib.error, urllib.request, urllib.error, urllib.parse
import json as simplejson
# Given a text string, remove all non-alphanumeric
# characters (using Unicode definition of alphanumeric).
def getQueries(text,n):
import re
sentenceEnders = re.compile('[.!?]')
sentenceList = sentenceEnders.split(text)
sentencesplits = []
for sentence in sentenceList:
x = re.compile(r'\W+', re.UNICODE).split(sentence)
x = [ele for ele in x if ele != '']
sentencesplits.append(x)
finalq = []
for sentence in sentencesplits:
l = len(sentence)
l=l/n
index = 0
for i in range(0,l):
finalq.append(sentence[index:index+n])
index = index + n-1
if index !=len(sentence):
finalq.append(sentence[len(sentence)-index:len(sentence)])
return finalq
# Search the web for the plagiarised text
# Calculate the cosineSimilarity of the given query vs matched content on google
# This is returned as 2 dictionaries
def searchWeb(text,output,c):
try:
text = text.encode('utf-8')
except:
text = text
query = urllib.parse.quote_plus(text)
if len(query)>60:
return output,c
#using googleapis for searching web
base_url = 'http://ajax.googleapis.com/ajax/services/search/web?v=1.0&q='
url = base_url + '%22' + query + '%22'
request = urllib.request.Request(url,None,{'Referer':'Google Chrome'})
response = urllib.request.urlopen(request)
results = simplejson.load(response)
try:
if ( len(results) and 'responseData' in results and 'results' in results['responseData'] and results['responseData']['results'] != []):
for ele in results['responseData']['results']:
Match = results['responseData']['results'][0]
content = Match['content']
if Match['url'] in output:
#print text
#print strip_tags(content)
output[Match['url']] = output[Match['url']] + 1
c[Match['url']] = (c[Match['url']]*(output[Match['url']] - 1) + cosineSim(text,strip_tags(content)))/(output[Match['url']])
else:
output[Match['url']] = 1
c[Match['url']] = cosineSim(text,strip_tags(content))
except:
return output,c
return output,c
# Use the main function to scrutinize a file for
# plagiarism
def main():
# n-grams N VALUE SET HERE
n=9
if len(sys.argv) <3:
print ("Usage: python main.py <input-filename>.txt <output-filename>.txt")
sys.exit()
if sys.argv[1].endswith(".docx"):
t = docxExtract(sys.argv[1])
else:
t=open(sys.argv[1],'r')
if not t:
print ("Invalid Filename")
print ("Usage: python main.py <input-filename>.txt <output-filename>.txt")
sys.exit()
t=t.read()
queries = getQueries(t,n)
q = [' '.join(d) for d in queries]
found = []
#using 2 dictionaries: c and output
#output is used to store the url as key and number of occurences of that url in different searches as value
#c is used to store url as key and sum of all the cosine similarities of all matches as value
output = {}
c = {}
i=1
count = len(q)
if count>100:
count=100
for s in q[:100]:
output,c=searchWeb(s,output,c)
msg = "\r"+str(i)+"/"+str(count)+"completed..."
sys.stdout.write(msg);
sys.stdout.flush()
i=i+1
#print ("\n")
f = open(sys.argv[2],"w")
for ele in sorted(iter(c.items()),key=operator.itemgetter(1),reverse=True):
f.write(str(ele[0])+" "+str(ele[1]*100.00))
f.write("\n")
f.close()
print ("\nDone!")
if __name__ == "__main__":
try:
main()
except:
#writing the error to stdout for better error detection
error = traceback.format_exc()
print(("\nUh Oh!\n"+"Plagiarism-Checker encountered an error!:\n"+error)) ```
docx, last release was in 2014. The code imports module exceptions that was a top-level module in Python 2.7 but was removed in Python 3:
$ python2.7 -c "import exceptions"
$ python3.7 -c "import exceptions"
Traceback (most recent call last):
File "<string>", line 1, in <module>
ModuleNotFoundError: No module named 'exceptions'
The bottom line: the package is only for Python 2. Use Python 2.7 or find a different package.
First of all I'm getting too many errors for python right now. This situation affected my motivation quite negatively. I'm trying to run an expert system that I found in this error. But I get the following error. I looked at other solutions but it didn't work for me either.
Drug Store Expert System:
https://github.com/enzoftware/pyswipl_drugstore
Code:
from flask import Flask, render_template, flash, request
from wtforms import Form, TextField, TextAreaField, validators, StringField, SubmitField
from pyswip import Prolog
import os
import time
# App config.
DEBUG = True
app = Flask(__name__)
app.config.from_object(__name__)
app.config['SECRET_KEY'] = '7d441f27d441f27567d441f2b6176a'
class ReusableForm(Form):
name = TextField('Name:', validators=[validators.required()])
#app.route("/", methods=['GET', 'POST'])
def hello():
form = ReusableForm(request.form)
if request.method == 'POST':
name=request.form['name']
fiebre = request.form.get('fiebre') == 'on'
nausea = request.form.get('nausea') == 'on'
diarrea = request.form.get('diarrea') == 'on'
headache = request.form.get('headache') == 'on'
print(fiebre, nausea, diarrea, headache)
os.system('swipl -q -t "program" console.pl')
if form.validate():
f = open("file.txt", "r")
disease = f.read()
print(disease)
flash('Hola ' + name + ', por tus sintomas podemos deducir que tienes '+ disease)
else:
flash('Error: Debes ingresar tu nombre. ')
return render_template('hello.html', form=form)
if __name__ == "__main__":
app.run()
Error:
ERROR: The system was unable to find the specified registry key or value.
Traceback (most recent call last):
File "c:/Users/BAUM-PC/Desktop/Yeni klasör/pyswipl_drugstore-master/main.py", line 3, in <module>
from pyswip import Prolog
File "c:\Users\BAUM-PC\Desktop\Yeni klasör\pyswipl_drugstore-master\pyswip\__init__.py", line 29, in <module>
from pyswip.prolog import Prolog
File "c:\Users\BAUM-PC\Desktop\Yeni klasör\pyswipl_drugstore-master\pyswip\prolog.py", line 28, in <module>
from pyswip.core import *
File "c:\Users\BAUM-PC\Desktop\Yeni klasör\pyswipl_drugstore-master\pyswip\core.py", line 568, in <module>
(_path, SWI_HOME_DIR) = _findSwipl()
File "c:\Users\BAUM-PC\Desktop\Yeni klasör\pyswipl_drugstore-master\pyswip\core.py", line 411, in _findSwipl
(path, swiHome) = _findSwiplWin()
File "c:\Users\BAUM-PC\Desktop\Yeni klasör\pyswipl_drugstore-master\pyswip\core.py", line 208, in _findSwiplWin
match = pattern.match(ret[-1])
IndexError: list index out of range
core.py
(related section)
try:
cmd = Popen(['reg', 'query',
r'HKEY_LOCAL_MACHINE\Software\SWI\Prolog',
'/v', 'home'], stdout=PIPE)
ret = cmd.communicate()
# Result is like:
# ! REG.EXE VERSION 3.0
#
# HKEY_LOCAL_MACHINE\Software\SWI\Prolog
# home REG_SZ C:\Program Files\pl
# (Note: spaces may be \t or spaces in the output)
ret = ret[0].splitlines()
ret = [line.decode("utf-8") for line in ret if len(line) > 0]
pattern = re.compile('[^h]*home[^R]*REG_SZ( |\t)*(.*)$')
match = pattern.match(ret[-1])
if match is not None:
path = match.group(2)
paths = [os.path.join(path, 'bin', dllName)
for dllName in dllNames]
for path in paths:
if os.path.exists(path):
return (path, None)
Windows Solution:
Make sure your Python and SWI Prolog are both 32- or 64-bit.
Go to line 180 of core.py and change the line to this:
paths = [os.path.join(programFiles, r'swipl\bin', dllName)
For first error:
As per official documentation of Pyswip you must take care of version of python and SWI-Prolog.
Make sure the SWI-Prolog architecture is the same as the Python architecture. If you are using a 64bit build of Python, use a 64bit build of SWI-Prolog.
For second error:
When you are accessing ret[-1] in match = pattern.match(ret[-1]) the index of list ret is not available.
I am trying to implement a captcha based on someone elses code using webpy. The code I am starting with is here: https://kzar.co.uk/blog/2009/07/14/web.py-captcha/
The example code there isn't complete, and I need to work out what to do with this app variable. Here is my code:
import web
from captcha import getCaptcha
render = web.template.render('templates/')
urls = (
'/([a-zA-Z]+/[a-zA-Z]+)', 'index',
'/', 'index',
'/captcha.gif', 'captcha'
)
if web.config.get("_session") is None:
session = web.session.Session(app, web.session.DiskStore('sessions'), initializer={'captcha': ''})
web.config._session = session
else:
session = web.config._session
vcaptcha = form.Validator('Please enter the code', lambda x:x == session.captcha)
enquiry_form = form.Form(
form.Textbox("captcha", vcaptcha, description="Validation Code", pre="<img src='/captcha.gif' valign=center><br>", class_="standard", style="width:70px;"),
)
class index:
def GET(self, argu = "Anonymous/Person"):
args = argu.split('/')
firstname = args[0]
if (len(args) >= 2):
lastname = args[1]
return render.index(firstname, lastname)
return render.index(firstname, "Snow")
class captcha:
def GET(self):
web.header("Content-Type", "image/gif")
captcha = getCaptcha
session.captcha = captcha[0]
return captcha[1].read()
if __name__ == "__main__":
app = web.application(urls, globals())
app.run()
It gives this error when ran:
$ python code.py
Traceback (most recent call last):
File "code.py", line 13, in <module>
session = web.session.Session(app, web.session.DiskStore('sessions'), initializer={'captcha': ''})
NameError: name 'app' is not defined
I've been looking at the webpy documentation and API reference, and I can't figure out what to do to properly initialise this 'app' variable.
You're using the as yet undefined app when you call session = web.session.Session(app, ...
Have you seen the documentation on sessions? See how they define app in the example prior to using it.
Just after URLs one is supposed to have this:
app = web.application(urls, globals())
I am currently working on a REST call using Flask Framework. and I have run into some errors along the way, which I am unable to figure out as to why they occur (still trying though). The error is as shown below:
[2016-09-20 18:53:26,486] ERROR in app: Exception on /Recommend [GET]
Traceback (most recent call last):
File "/anaconda/lib/python2.7/site-packages/flask/app.py", line 1988, in wsgi_app
response = self.full_dispatch_request()
File "/anaconda/lib/python2.7/site-packages/flask/app.py", line 1641, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/anaconda/lib/python2.7/site-packages/flask_cors/extension.py", line 161, in wrapped_function
return cors_after_request(app.make_response(f(*args, **kwargs)))
File "/anaconda/lib/python2.7/site-packages/flask_api/app.py", line 97, in handle_user_exception
for typecheck, handler in chain(blueprint_handlers.items(), app_handlers.items()):
AttributeError: 'tuple' object has no attribute 'items'
127.0.0.1 - - [20/Sep/2016 18:53:26] "GET /Recommend HTTP/1.1" 500 -
here is the code that I have built:
from flask import request, jsonify
from flask_api import FlaskAPI
from flask_cors import CORS
from sets import Set
from collections import defaultdict
import itertools
import copy
app = FlaskAPI(__name__)
CORS(app)
content = None
class Apriori:
def __init__(self):
self.no_of_transactions = None
self.min_support = 0.5
self.min_confidence = 0.75
self.transactions = {}
self.set_of_items = set()
self.frequencies = {}
self.frequent_itemsets_of_order_n = {}
self.association_rules = {}
def createPowerSet(self,s):
powerset = set()
for i in xrange(2**len(s)):
subset = tuple([x for j,x in enumerate(s) if (i >> j) & 1])
if len(subset) == 0:
pass
elif len(subset) == 1:
powerset.add(subset[0])
else:
powerset.add(subset)
return powerset
def createFrequentItemSets(self,set_of_items,len):
frequent_itemsets = set(itertools.combinations(set_of_items, len))
for i in list(frequent_itemsets):
tempset = set(i)
self.frequencies[i] = 0
for k, v in self.transactions.iteritems():
if tempset.issubset(set(v)):
self.frequencies[i] += 1
if float(self.frequencies[i])/self.no_of_transactions < self.min_support:
frequent_itemsets.discard(i)
return frequent_itemsets
def mineAssociationRules(self,frequent_itemset):
s = set(frequent_itemset)
subs = list(self.createPowerSet(s))
for each in subs:
if sorted(tuple(set(each))) == sorted(tuple(s)):
continue
if len(set(each))==1:
antecedent = list(set(each))[0]
elif len(set(each))>1:
antecedent = tuple(set(each))
if len(s.difference(set(each)))==1:
consequent = list(s.difference(set(each)))[0]
elif len(s.difference(set(each)))>1:
consequent = tuple(s.difference(set(each)))
AuC = tuple(s)
if float(self.frequencies[AuC])/self.frequencies[antecedent] >= self.min_confidence:
if antecedent in self.association_rules:
pass
else:
if type(antecedent) is tuple:
antecedent = (",").join(antecedent)
if type(consequent) is tuple:
consequent = (",").join(consequent)
self.association_rules[antecedent] = consequent
def implement(self,transactions):
#for i in range(0,self.no_of_transactions):
for i in range(0,len(transactions)):
self.transactions["T"+str(i)] = defaultdict(list)
self.transactions["T"+str(i)] = transactions[i].split(',')
self.set_of_items = self.set_of_items.union(Set(self.transactions["T"+str(i)]))
for i in list(self.set_of_items):
self.frequencies[i] = 0
for k, v in self.transactions.iteritems():
if i in v:
self.frequencies[i] = self.frequencies[i] + 1
if float(self.frequencies[i])/self.no_of_transactions < self.min_support:
self.set_of_items.discard(i)
self.frequent_itemsets_of_order_n[1] = self.set_of_items
l = 1
reps = copy.deepcopy(self.set_of_items)
while True:
l += 1
result = self.createFrequentItemSets(self.set_of_items, l)
if len(result) == 0:
break
self.frequent_itemsets_of_order_n[l] = result
reps = copy.deepcopy(self.frequent_itemsets_of_order_n[l])
l = l-1
while l>2:
for each in self.frequent_itemsets_of_order_n[l]:
self.mineAssociationRules(each)
l = l-1
#app.route('/Recommend')
def FindAssociations():
transactions = ["A,C,D,F,G","A,B,C,D,F","C,D,E","A,D,F","A,C,D,E,F","B,C,D,E,F,G"]
apr = Apriori()
apr.implement(transactions)
return jsonify(rules=apr.association_rules)
if __name__ == "__main__":
app.run(port=5000)
I did run some sample code found on the web, and built the above script based on those scripts. They worked out well. The class I built was based on another python program that I had built earlier which worked well. Should I have imported the class from another script instead of building it here?
There are a number of errors in your Apriori which need to fixed. There are a few attempts to divide by self.no_of_transactions (e.g. line 87) which is initialised to None and never changed. Dividing by None raises an exception:
>>> 1/None
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for /: 'int' and 'NoneType'
This exception is then handled in Flask-API's handle_user_exception() method, which also appears to have a bug as shown in the exception it raises.
The way to fix it is to correct your code so that it does not divide by None.
I'm very new to Python, my requirement is that i have CQ webpage and need to update the status of BugID based on particular fields.
Here is the sample code i'm trying.
import httplib2
import json
import getpass
import urllib
from string import Template
from xml.dom.minidom import parseString
class Credentials():
def assign_user (self):
self._user = 'user'
def assign_passwd (self):
self._passwd = 'pawrd'
user_cred = Credentials()
class RestLink:
def __init__(self, link, baseline_cr= 'ENGR00xxxx'):
self._link = Template(link)
self.cr = baseline_cr
def get_link(self):
return self._link.safe_substitute(recordId=self.cr,
loginid=user_cred.get_user(),
password=user_cred.get_passwd())
class CQBase:
SERVER = 'cq.am.domain.net'
RESPONSE_OK = 'OK'
def __init__(self, logger):
self._logger = logger
def send_request(self):
data = ''
try:
conn = httplib2.HTTPConnectionWithTimeout(self.SERVER)
conn.request("GET", link)
res = conn.getresponse()
data = res.read()
if res.reason != self.RESPONSE_OK:
raise ParseException('Cannot execute request!')
conn.close()
except:
conn.close()
raise
return data
class CQIssueReader(CQBase):
VIEW_CR_LINK = '/cqweb/restapi/TSR/ENGR/RECORD/${recordId}?format=JSON&recordType=CR&loginId=${loginid}&password=${password}&noframes=true'
def __init__(self, cr, logger):
CQBase.__init__(self, logger)
self._cr = cr
self._headline = ''
self._subtype = ''
self._branch = ''
self._is_resolved = 0
self._is_integrated = 0
self.parse_cr()
def parse_cr(self):
self._is_resolved = False
self._is_integrated = False
data = self.send_request(RestLink(self.VIEW_CR_LINK, self._cr).get_link())
parsedData = json.loads(data)
for field in parsedData['fields']:
if field['FieldName'] == 'Headline':
self._headline = field['CurrentValue']
if field['FieldName'] == 'Integrated':
self._logger.log_details('\tIntegrated = ' + field['CurrentValue'])
if field['CurrentValue'] == 'Y':
self._is_integrated = True
if field['FieldName'] == 'State':
self._logger.log_details('\tState = ' + field['CurrentValue'])
if (field['CurrentValue'] == 'Resolved') or (field['CurrentValue'] == 'Closed')\
or (field['CurrentValue'] == 'Verified'):
self._is_resolved = True
if field['FieldName'] == 'Subtype':
self._subtype = field['CurrentValue']
if field['FieldName'] == 'BranchName':
self._branch = field['CurrentValue']
self._logger.log_details('\tBranchName = ' + self._branch)
def get_headline(self):
return self._headline
def get_subtype(self):
return self._subtype
def get_branch_name(self):
return self._branch
test = CQIssueReader(CQBase)
test_data = CQIssueReader.parse_cr()
print (test_data)
i get following error with above code:
Traceback (most recent call last):
File "test.py", line 97, in <module>
test = CQIssueReader(CQBase)
TypeError: __init__() missing 1 required positional argument: 'logger'
Kindly guide me where i'm going wrong.
According to def __init__(self, cr, logger): your Class needs a parameter called logger to work. In test = CQIssueReader(CQBase), you've not passed in a logger.