Related
I have the following Graphene implementation:
import graphene
import json
import psycopg2
import re
connection = psycopg2.connect(user='postgres', password='Steppen1!', host='127.0.0.1', port='5432', database='TCDigital')
cursor = connection.cursor()
paths = {}
class PathError(Exception):
def __init__(self, referencing, referenced):
self.message = "entity {} has no relation with entity {}".format(referencing, referenced)
def __str__(self):
return self.message
def get_columns(entity):
columns = {}
cursor.execute("SELECT ordinal_position, column_name FROM information_schema.columns WHERE table_name = '{}'".format(entity))
resultset = cursor.fetchall()
i = 1
for entry in resultset:
columns[entry[1]] = i
i = i + 1
return columns
def get_previous_annotate(name, entity, related_column, id):
columns = get_columns(entity)
related_position = columns[related_column]-1
entity_content = paths[name][entity]
entity_content_filtered = [entry for entry in entity_content if entry['entry'][related_position] == id]
annotate_to_return = sum(list(map(lambda entry: entry['annotate'], entity_content_filtered)))
return annotate_to_return
def calculate_annotate_operation(entity, entry, entity_columns, operation, operands):
operand1 = entity_columns[operands[0]]
operand2 = entity_columns[operands[1]]
if operation == '_sum':
return entry[operand1] + entry[operand2]
elif operation == '_mult':
return entry[operand1] * entry[operand2]
elif operation == '_div':
return entry[operand1] / entry[operand2]
elif operation == '_rest':
return entry[operand1] - entry[operand2]
else:
return None
def get_annotated_value(name, entity, entry, annotate, entity_columns):
if annotate[0] != '_':
column = entity_columns[annotate]
column_value = entity[column['ordinal_position']]
return column_value
elif annotate == '_count':
return 1
else:
operation = annotate.split('(')
if operation[0] in ['_sum', '_mult', '_div', '_rest']:
operands_base = operation[1].split(')')[0]
operands = operands_base.split(',')
return calculate_annotate_operation(operation[0], operands)
else:
raise "Operación no permitida: {}".format(annotate)
def get_annotate(name, entity, entry, entity_columns, previous_entity, related_column, annotate):
annotated_value = None
previous_entity_columns = get_columns(previous_entity)
if previous_entity:
annotated_value = get_previous_annotate(name, previous_entity, related_column, entry[entity_columns['id']-1])
else:
annotated_value = get_annotated_value(name, entity, entry, annotate, entity_columns)
#print({'name': name, 'entity': entity, 'entry': entry, 'annotated_value': annotated_value})
return annotated_value
def populate_entity(name, entity, entity_columns, previous_entity, previous_entity_relationship_column, annotate):
cursor.execute('SELECT * FROM {}'.format(entity))
resultset = cursor.fetchall()
paths[name][entity] = []
for entry in resultset:
if previous_entity:
entry_annotate = get_annotate(name, entity, entry, entity_columns, previous_entity, previous_entity_relationship_column, annotate)
else:
entry_annotate = get_annotate(name, entity, entry, entity_columns, previous_entity, None, annotate)
paths[name][entity].append({'entry': entry, 'entity_columns': entity_columns, 'annotate': entry_annotate, 'previos_entity': previous_entity, 'previous_entity_relationship_column': previous_entity_relationship_column})
def create_path(name, entities, annotate):
paths[name] = {}
previous_entity = None
for entity in reversed(entities):
previous_entity_relationship_column = None
if previous_entity:
previous_entity_relationships = get_foreign_relationships(previous_entity)
previous_entity_relationship = [relationship for relationship in previous_entity_relationships if relationship[5] == entity][0]
previous_entity_relationship_column = previous_entity_relationship[3]
entity_columns = get_columns(entity)
populate_entity(name, entity, entity_columns, previous_entity, previous_entity_relationship_column, annotate)
previous_entity = entity
def get_foreign_relationships(entity):
cursor.execute('''
SELECT
tc.table_schema, tc.constraint_name, tc.table_name, kcu.column_name, ccu.table_schema AS foreign_table_schema, ccu.table_name AS foreign_table_name, ccu.column_name AS foreign_column_name
FROM information_schema.table_constraints AS tc
JOIN information_schema.key_column_usage AS kcu ON tc.constraint_name = kcu.constraint_name
AND tc.table_schema = kcu.table_schema
JOIN information_schema.constraint_column_usage AS ccu ON ccu.constraint_name = tc.constraint_name
AND ccu.table_schema = tc.table_schema
WHERE tc.constraint_type = 'FOREIGN KEY' AND tc.table_name='{}';'''.format(entity))
result = cursor.fetchall()
result_array = []
for record in result:
new_entity = Entity(name=record[5])
result_array.append(new_entity)
return result
def is_relationship(referencing, referenced):
foreign_relationships = get_foreign_relationships(referencing)
if referenced in list(map(lambda relationship: relationship[5], foreign_relationships)):
return True
else:
return False
def traverse(entities, direction):
for i in range(len(entities)):
if i > 0 and i < len(entities)-1:
if not is_relationship(entities[i], entities[i-1]):
raise PathError(entities[i], entities[i-1])
return True
def validate_path(path):
entities = path.split('/')
traverse(entities, 'forward')
return entities
def get_path_step(name, step, key):
content = paths[name][step]
if key is None:
filtered_content = [{'entry': entry['entry'], 'annotate': entry['annotate']} for entry in content]
else:
if content['previous_entity_relationship_column'] is not None:
previous_entity_relationship_column = content['previous_entity_relationship_column']
relationship_column_index = content['entity_columns'][previous_entity_relationship_column]
filtered_content = [{'entry': entry['entry'], 'annotate': entry['annotate']} for entry in content if entry[relationship_column_index] == key]
return filtered_content
class Entity(graphene.ObjectType):
name = graphene.String()
annotate = graphene.Float()
content = graphene.Field(graphene.List(lambda: Entity))
class Query(graphene.ObjectType):
entity_relationships = graphene.List(Entity, entity=graphene.String())
postgresql_version = graphene.String
path = graphene.String(name=graphene.String(), path=graphene.String(), annotate=graphene.String(), current=graphene.String(), key=graphene.Int())
path_step = graphene.String(name=graphene.String(), step=graphene.String(), key=graphene.Int())
#staticmethod
def resolve_path_step(parent, info, name, step, key):
path_step = get_path_step(name, step, key)
print(name)
print(step)
print(key)
print(path_step)
return path_step
#staticmethod
def resolve_path(parent, info, name, path, annotate, current, key):
entities = validate_path(path)
create_path(name, entities, annotate)
content_to_return = get_path_step(name, entities[0], None)
return content_to_return
#staticmethod
def resolve_entity_relationships(parent, info, entity):
result_array = get_foreign_relationships(entity)
return result_array
#staticmethod
def resolve_postgresql_version(parent, info):
cursor.execute("SELECT version();")
record = cursor.fetchone()
return record
def execute_query(query_to_execute):
queries = {
'postgresqlVersion': '''
{
postgresqlVersion
}
''',
'entityRelationships': '''
{
entityRelationships (entity: "inventory_productitem") {
name
}
}
''',
'path': '''
{
path(name: "Ventas", path: "general_state/general_city/inventory_store/operations_sale", annotate: "_count", current: "inventory_product", key: 0)
}
''',
'path_step': '''
{
path_step(name: "Ventas", step: "inventory_store", key: 27)
}
'''
}
schema = graphene.Schema(query=Query)
result = schema.execute(queries[query_to_execute])
dict_result = dict(result.data.items())
print(json.dumps(dict_result, indent=2))
result2 = schema.execute(queries['path_step'])
dict_result2 = dict(result2.data.items())
print(json.dumps(dict_result2, indent=2))
execute_query('path')
Te first call to schema.execute() works with no problem, but the second one doesn't even enter the resolver, and the only error message I get is:
Traceback (most recent call last):
File "query.py", line 249, in <module>
execute_query('path')
File "query.py", line 246, in execute_query
dict_result2 = dict(result2.data.items())
AttributeError: 'NoneType' object has no attribute 'items'
I don't know what I am missing.
I have found that the problem was that I am making a pythonic pascal-cased call to Graphene query: path_step(name: "Ventas", step: "inventory_store", key: 27), but Graphene requieres queries to be called on a camel-cased fashion, even when the name of the resolvers and query variables are pascal-cased in the code.
So the call to the query must by camel-cased like this: pathStep(name: "Ventas", step: "inventory_store", key: 27)
i am getting following error- "Python: TypeError:string indices must be integers" and I can not see what's wrong. Am I being stupid and overlooking an obvious mistake here?
class Order_ListAPIView(APIView):
def get(self,request,format=None):
totalData=[]
if request.method == 'GET':
cur,conn = connection()
order_query = ''' SELECT * FROM orders'''
order_detail_query = ''' SELECT * FROM order_details'''
with conn.cursor(MySQLdb.cursors.DictCursor) as cursor:
cursor.execute(order_detail_query)
order_detail_result = cursor.fetchall()
order_detail_data = list(order_detail_result)
# print(order_detail_data)
cursor.execute(order_query)
order_result = cursor.fetchall()
order_data = list(order_result)
dic = {}
for d in order_detail_query:
if d['order_id'] not in dic:
dic[d['order_id']] = []
dic[d['order_id']].append(d)
return order_data.append(dic)
totalData.append({"order_data":order_data, "order_detail_data":order_detail_data})
return Response({"totalData":totalData,},status=status.HTTP_200_OK)
else:
return Response(status=status.HTTP_400_BAD_REQUEST)
lass Order_ListAPIView(APIView):
def get(self,request,format=None):
totalData=[]
if request.method == 'GET':
cur,conn = connection()
order_query = ''' SELECT * FROM orders'''
order_detail_query = ''' SELECT * FROM order_details'''
with conn.cursor(MySQLdb.cursors.DictCursor) as cursor:
cursor.execute(order_detail_query)
order_detail_result = cursor.fetchall()
order_detail_data = list(order_detail_result)
# print(order_detail_data)
cursor.execute(order_query)
order_result = cursor.fetchall()
order_data = list(order_result)
dic = {}
for d in order_detail_data:
if d['order_id'] not in dic:
dic[d['order_id']] = []
dic[d['order_id']].append(d)
return order_data.append(dic)
totalData.append({"order_data":order_data, "order_detail_data":order_detail_data})
return Response({"totalData":totalData,},status=status.HTTP_200_OK)
else:
return Response(status=status.HTTP_400_BAD_REQUEST)
This should work
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I am new to Python I got an error at class def line. I am not sure what mistake I have done. Please check it and let me know.
class contactservices():
def GetDirectorySearchList(userId:int, searchKey,result:ContactResultSet):
ret = RETURN_CODE.RECORD_NOT_EXISTS
cursor = connections['default'].cursor()
rows =""
invalid syntax (contactservices.py, line 15)
Thanks in advance.
Full Code:
from django.db import connections
from api.enums import RETURN_CODE
from api.user.contactmodel import ContactModel
from api.user.contactmodel import DirectoryModel
from api.user.resultset import ContactResultSet
from api.datalayer.dbservices import dbservices
class contactservices():
"""Get Directory Search of a specific user"""
def GetDirectorySearchList(userId:int, searchKey, result:ContactResultSet):
ret = RETURN_CODE.RECORD_NOT_EXISTS
cursor = connections['default'].cursor()
rows =""
try:
#user triple quote for multiline string.
msqlquery = """SELECT a.id, username, first_name, last_name, firm,email,extension, extpassword,start_date,expiry_date,status,presence_status
,aliasname,picturepath,statusupdatedate
FROM ocktopi_login a where (first_name LIKE '%%""" + str(searchKey) + "%%' OR last_name LIKE '%%" + str(searchKey) + "%%' OR aliasname LIKE '%%" + str(searchKey) + "%%') AND id NOT IN (select contact from usercontactmapping where user = """ + str(userId) + ") and id <> " + str(userId) + "";
#cursor.execute(msqlquery)
rows = dbservices.query_to_dicts(msqlquery)
ret = RETURN_CODE.RECORD_EXISTS
except Exception as e:
ret = RETURN_CODE.RECORD_ERROR
#We dont have a way to map with column name . So only solution is column index.Changed to dictory using a method now.
directorylist = list()
for row in rows:
directory = DirectoryModel()
directory.Id = row['id']
directory.Username = row['username']
directory.FirstName = row['first_name']
directory.LastName = row['last_name']
directory.Firm = row['firm']
directory.Email = row['email']
directory.Extension = row['extension']
directory.Status = row['status']
directory.PresenceStatus = row['presence_status']
directory.AliasName = row['aliasname']
directory.Picturepath = row['picturepath']
directorylist.append(directory)
result.ReturnCode = int(ret)
return directorylist
"""Get Contact Details of a specific user"""
def GetContactList(userId:int, result:ContactResultSet):
ret = RETURN_CODE.RECORD_NOT_EXISTS
cursor = connections['default'].cursor()
rows =""
try:
#user triple quote for multiline string.
msqlquery = """SELECT a.id, username, first_name, last_name, firm,email,extension, extpassword,start_date,expiry_date,status,presence_status
,aliasname,picturepath,statusupdatedate
FROM ocktopi_login a inner join usercontactmapping b on a.id=b.contact and a.id <> """ + str(userId) + " and b.user= " + str(userId) + "";
rows = dbservices.query_to_dicts(msqlquery)
ret = RETURN_CODE.RECORD_EXISTS
except Exception as e:
ret = RETURN_CODE.RECORD_ERROR
#We dont have a way to map with column name . So only solution is column index.Changed to dictory using a method now.
contactlist = list()
for row in rows:
contact = ContactModel()
contact.Id = row['id']
contact.Username = row['username']
contact.FirstName = row['first_name']
contact.LastName = row['last_name']
contact.Firm = row['firm']
contact.Email = row['email']
contact.Extension = row['extension']
contact.Status = row['status']
contact.PresenceStatus = row['presence_status']
contact.AliasName = row['aliasname']
contact.Picturepath = row['picturepath']
contactlist.append(contact)
result.ReturnCode = int(ret)
return contactlist
"""Add user contact"""
def AddUserContact(userId:int, contactId:int):
ret = 0
cursor = connections['default'].cursor()
rows =""
try:
msqlquery = """insert into usercontactmapping (user,contact) values(%s, %s)""";
cursor.execute(msqlquery,(userId, contactId))
ret = cursor.rowcount
return ret
except Exception as e:
ret = -1
finally:
cursor.close()
return ret
"""Remove user contact"""
def RemoveUserContact(userId:int, contactId:int):
ret = 0
cursor = connections['default'].cursor()
rows =""
try:
msqlquery = """delete from usercontactmapping where user=%s and contact=%s""";
cursor.execute(msqlquery,(userId, contactId))
ret = cursor.rowcount
return ret
except Exception as e:
ret = -1
finally:
cursor.close()
return ret
Try:
def GetDirectorySearchList(userId, searchKey,result):
ret = RETURN_CODE.RECORD_NOT_EXISTS
cursor = connections['default'].cursor()
rows = ""
Annotations such as userId:int don't work in Python 2.7.
Also make sure the code is indented properly.
So, I'm using Python with PyQt and I have a very strange problem. A string that prints OK at one point doesn't print OK after a few lines of code! Here's my code:
name = str(self.lineEdit.text().toUtf8())
self.let_change = Search()
name_no_ind = self.let_change.indentation(name)
print(name_no_ind)
name_cap = self.let_change.capital(name)
name_low = self.let_change.lower(name)
print(name_no_ind, name_cap, name_low)
col = self.combobox.currentIndex()
row = 0
for i in range(0, self.tableWidget.rowCount()):
try:
find_no_ind = self.let_change.indentation(self.tableWidget.item(row, col).text())
find_cap = self.let_change.capital(self.tableWidget.item(row, col).text())
find_lower = self.let_change.lower(self.tableWidget.item(row, col).text())
if name_no_ind or name_cap or name_low in find_no_ind or find_cap or find_lower:
self.tableWidget.setItemSelected(self.tableWidget.item(row, col), True)
print("Item found in %d, %d" % (row,col))
row += 1
except AttributeError:
row += 1
And here's what I get:
Αντωνης
('\xce\x91\xce\xbd\xcf\x84\xcf\x89\xce\xbd\xce\xb7\xcf\x82', '\xce\x91\xce\x9d\xce\xa4\xcf\x8e\xce\x9d\xce\x97\xce\xa3', '\xce\xb1\xce\xbd\xcf\x84\xcf\x8e\xce\xbd\xce\xb7\xcf\x82')
Item found in 0, 0
Isn't that strange? It prints OK and then it doesn't. Does anybody know what can I do?
P.S.: Here are the functions:
# -*- coding: utf-8 -*-
class Search():
#A function that removes indentations:
def indentation(self, name):
a = name
b = ["ά", "Ά", "ή", "Ή", "ώ", "Ώ", "έ", "Έ", "ύ", "Ύ", "ί", "Ί", "ό", "Ό"]
c = ['α', 'Α', 'η', 'Η', 'ω', 'Ω', 'ε', 'Ε', 'υ', 'Υ', 'ι', 'Ι', 'ο', 'Ο']
for i in b:
a = a.replace(i, c[b.index(i)])
return a
# A function that makes letters capital:
def capital(self, name):
a = name
greek_small = ["α", "β", "γ", "δ", "ε", "ζ", "η", "θ", "ι", "κ", "λ", "μ", "ν", "ξ", "ο", "π", "ρ", "σ", "τ", "υ", "φ", "χ", "ψ", "ω", "ς"]
greek_capital = ["Α", "Β", "Γ", "Δ", "Ε", "Ζ", "Η", "Θ", "Ι", "Κ", "Λ", "Μ", "Ν", "Ξ", "Ο", "Π", "Ρ", "Σ", "Τ", "Υ", "Φ", "Χ", "Ψ", "Ω", "Σ"]
for i in greek_small:
a = a.replace(i, greek_capital[greek_small.index(i)])
return a
#A function that makes letters lower:
def lower(self, name):
a = name
greek_small = ["α", "β", "γ", "δ", "ε", "ζ", "η", "θ", "ι", "κ", "λ", "μ", "ν", "ξ", "ο", "π", "ρ", "σ", "τ", "υ", "φ", "χ", "ψ", "ω", "ς"]
greek_capital = ["Α", "Β", "Γ", "Δ", "Ε", "Ζ", "Η", "Θ", "Ι", "Κ", "Λ", "Μ", "Ν", "Ξ", "Ο", "Π", "Ρ", "Σ", "Τ", "Υ", "Φ", "Χ", "Ψ", "Ω", "Σ"]
for i in greek_capital:
a = a.replace(i, greek_small[greek_capital.index(i)])
return a
Basically, it capitalizes or lowers Greek characters...
SOLUTION!!!:
Steve solved the initial problem and based on what he said, I came up with this that solves everything:
name = str(self.lineEdit.text().toUtf8())
self.let_change = Search()
name_no_ind = self.let_change.indentation(name)
name_cap = self.let_change.capital(name)
name_low = self.let_change.lower(name)
name_list = [name, name_no_ind, name_cap, name_low]
col = self.combobox.currentIndex()
row = 0
for i in range(0, self.tableWidget.rowCount()):
try:
item_ = str(self.tableWidget.item(row, col).text().toUtf8())
find_no_ind = self.let_change.indentation(item_)
find_cap = self.let_change.capital(item_)
find_lower = self.let_change.lower(item_)
item_list = [find_no_ind, find_cap, find_lower]
for x in name_list:
for y in item_list:
if x in y:
self.tableWidget.setItemSelected(self.tableWidget.item(row, col), True)
row += 1
except AttributeError:
row += 1
I would say that one r both of self.let_change.capital(name) or self.let_change.lower(name) is overwriting it by using the name of the input parameter or possibly changing the encoding. Since you have not posted the code for them I can not be sure.
Sorry, they are not the problem. The problem is that you are printing them differently:
>>> print(capital(name))
ΑΝΤΩΝΗΣ
>>> print(capital(name), name)
('\xce\x91\xce\x9d\xce\xa4\xce\xa9\xce\x9d\xce\x97\xce\xa3', '\xce\x91\xce\xbd\xcf\x84\xcf\x89\xce\xbd\xce\xb7\xcf\x82')
>>> print(capital(name))
ΑΝΤΩΝΗΣ
>>> print(name, name)
('\xce\x91\xce\xbd\xcf\x84\xcf\x89\xce\xbd\xce\xb7\xcf\x82', '\xce\x91\xce\xbd\xcf\x84\xcf\x89\xce\xbd\xce\xb7\xcf\x82')
>>> print(name,)
('\xce\x91\xce\xbd\xcf\x84\xcf\x89\xce\xbd\xce\xb7\xcf\x82',)
>>> print(name)
Αντωνης
>>> print("%s = %s" % (name, capital(name)))
Αντωνης = ΑΝΤΩΝΗΣ
>>>
So you either need separate print statements or the use of a format string.
At beginning i wanna say i'm newbie in use Python and everything I learned it came from tutorials.
My problem concerning reference to the value. I'm writing some script which is scrapping some information from web sites. I defined some function:
def MatchPattern(count):
sock = urllib.urlopen(Link+str(count))
htmlSource = sock.read()
sock.close()
root = etree.HTML(htmlSource)
root = etree.HTML(htmlSource)
result = etree.tostring(root, pretty_print=True, method="html")
expr1 = check_reg(root)
expr2 = check_practice(root)
D_expr1 = no_ks(root)
D_expr2 = Registred_by(root)
D_expr3 = Name_doctor(root)
D_expr4 = Registration_no(root)
D_expr5 = PWZL(root)
D_expr6 = NIP(root)
D_expr7 = Spec(root)
D_expr8 = Start_date(root)
#-----Reg_practice-----
R_expr1 = Name_of_practise(root)
R_expr2 = TERYT(root)
R_expr3 = Street(root)
R_expr4 = House_no(root)
R_expr5 = Flat_no(root)
R_expr6 = Post_code(root)
R_expr7 = City(root)
R_expr8 = Practice_no(root)
R_expr9 = Kind_of_practice(root)
#------Serv_practice -----
S_expr1 = TERYT2(root)
S_expr2 = Street2(root)
S_expr3 = House_no2(root)
S_expr4 = Flat_no2(root)
S_expr5 = Post_code2(root)
S_expr6 = City2(root)
S_expr7 = Phone_no(root)
return expr1
return expr2
return D_expr1
return D_expr2
return D_expr3
return D_expr4
return D_expr5
return D_expr6
return D_expr7
return D_expr8
#-----Reg_practice-----
return R_expr1
return R_expr2
return R_expr3
return R_expr4
return R_expr5
return R_expr6
return R_expr7
return R_expr8
return R_expr9
#------Serv_practice -----
return S_expr1
return S_expr2
return S_expr3
return S_expr4
return S_expr5
return S_expr6
return S_expr7
So now inside the script I wanna check value of the expr1 returned by my fynction. I don't know how to do that. Can u guys help me ? Is my function written correct ?
EDIT:
I can't add answer so I edit my current post
This is my all script. Some comments are in my native language but i add some in english
#! /usr/bin/env python
#encoding:UTF-8-
# ----------------------------- importujemy potrzebne biblioteki i skrypty -----------------------
# ------------------------------------------------------------------------------------------------
import urllib
from lxml import etree, html
import sys
import re
import MySQLdb as mdb
from TOR_connections import *
from XPathSelection import *
import os
# ------------------------------ Definiuje xPathSelectors ------------------------------------------
# --------------------------------------------------------------------------------------------------
# -------Doctors -----
check_reg = etree.XPath("string(//html/body/div/table[1]/tr[3]/td[2]/text())") #warunek Lekarz
check_practice = etree.XPath("string(//html/body/div/table[3]/tr[4]/td[2]/text())") #warunek praktyka
no_ks = etree.XPath("string(//html/body/div/table[1]/tr[1]/td[2]/text())")
Registred_by = etree.XPath("string(//html/body/div/table[1]/tr[4]/td[2]/text())")
Name_doctor = etree.XPath("string(//html/body/div/table[2]/tr[2]/td[2]/text())")
Registration_no = etree.XPath("string(//html/body/div/table[2]/tr[3]/td[2]/text())")
PWZL = etree.XPath("string(//html/body/div/table[2]/tr[4]/td[2]/text())")
NIP = etree.XPath("string(//html/body/div/table[2]/tr[5]/td[2]/text())")
Spec = etree.XPath("string(//html/body/div/table[2]/tr[18]/td[2]/text())")
Start_date = etree.XPath("string(//html/body/div/table[2]/tr[20]/td[2]/text())")
#-----Reg_practice-----
Name_of_practise = etree.XPath("string(//html/body/div/table[2]/tr[1]/td[2]/text())")
TERYT = etree.XPath("string(//html/body/div/table[2]/tr[7]/td[2]/*/text())")
Street = etree.XPath("string(//html/body/div/table[2]/tr[8]/td[2]/text())")
House_no = etree.XPath("string(//html/body/div/table[2]/tr[9]/td[2]/*/text())")
Flat_no = etree.XPath("string(//html/body/div/table[2]/tr[10]/td[2]/*/text())")
Post_code = etree.XPath("string(//html/body/div/table[2]/tr[11]/td[2]/*/text())")
City = etree.XPath("string(//html/body/div/table[2]/tr[12]/td[2]/*/text())")
Practice_no = etree.XPath("string(//html/body/div/table[3]/tr[4]/td[2]/text())")
Kind_of_practice = etree.XPath("string(//html/body/div/table[3]/tr[5]/td[2]/text())")
#------Serv_practice -----
TERYT2 = etree.XPath("string(//html/body/div/table[3]/tr[14]/td/table/tr[2]/td[2]/*/text())")
Street2 = etree.XPath("string(//html/body/div/table[3]/tr[14]/td/table/tr[3]/td[2]/text())")
House_no2 = etree.XPath("string(//html/body/div/table[3]/tr[14]/td/table/tr[4]/td[2]/*/text())")
Flat_no2 = etree.XPath("string(//html/body/div/table[3]/tr[14]/td/table/tr[5]/td[2]/i/text())")
Post_code2 = etree.XPath("string(//html/body/div/table[3]/tr[14]/td/table/tr[6]/td[2]/*/text())")
City2 = etree.XPath("string(//html/body/div/table[3]/tr[14]/td/table/tr[7]/td[2]/*/text())")
Phone_no = etree.XPath("string(//html/body/div/table[3]/tr[14]/td/table/tr[8]/td[2]/text())")
# --------------------------- deklaracje zmiennych globalnych ----------------------------------
# ----------------------------------------------------------------------------------------------
decrease = 9
No = 1
Link = "http://rpwdl.csioz.gov.pl/rpz/druk/wyswietlKsiegaServletPub?idKsiega="
# --------------------------- funkcje zdefiniowane ----------------------------------
# ----------------------------------------------------------------------------------------------
def MatchPattern(count):
sock = urllib.urlopen(Link+str(count))
htmlSource = sock.read()
sock.close()
root = etree.HTML(htmlSource)
root = etree.HTML(htmlSource)
result = etree.tostring(root, pretty_print=True, method="html")
expr1 = check_reg(root)
expr2 = check_practice(root)
D_expr1 = no_ks(root)
D_expr2 = Registred_by(root)
D_expr3 = Name_doctor(root)
D_expr4 = Registration_no(root)
D_expr5 = PWZL(root)
D_expr6 = NIP(root)
D_expr7 = Spec(root)
D_expr8 = Start_date(root)
#-----Reg_practice-----
R_expr1 = Name_of_practise(root)
R_expr2 = TERYT(root)
R_expr3 = Street(root)
R_expr4 = House_no(root)
R_expr5 = Flat_no(root)
R_expr6 = Post_code(root)
R_expr7 = City(root)
R_expr8 = Practice_no(root)
R_expr9 = Kind_of_practice(root)
#------Serv_practice -----
S_expr1 = TERYT2(root)
S_expr2 = Street2(root)
S_expr3 = House_no2(root)
S_expr4 = Flat_no2(root)
S_expr5 = Post_code2(root)
S_expr6 = City2(root)
S_expr7 = Phone_no(root)
return expr1
return expr2
return D_expr1
return D_expr2
return D_expr3
return D_expr4
return D_expr5
return D_expr6
return D_expr7
return D_expr8
#-----Reg_practice-----
return R_expr1
return R_expr2
return R_expr3
return R_expr4
return R_expr5
return R_expr6
return R_expr7
return R_expr8
return R_expr9
#------Serv_practice -----
return S_expr1
return S_expr2
return S_expr3
return S_expr4
return S_expr5
return S_expr6
return S_expr7
# --------------------------- ustanawiamy polaczenie z baza danych -----------------------------
# ----------------------------------------------------------------------------------------------
con = mdb.connect('localhost', 'root', '******', 'SANBROKER', charset='utf8');
# ---------------------------- początek programu -----------------------------------------------
# ----------------------------------------------------------------------------------------------
with con:
cur = con.cursor()
cur.execute("SELECT Old_num FROM SANBROKER.Number_of_records;")
Old_num = cur.fetchone()
count = Old_num[0]
counter = input("Input number of rows: ")
# ----------------------- pierwsze połączenie z TORem ------------------------------------
# ----------------------------------------------------------------------------------------
#connectTor()
#conn = httplib.HTTPConnection("my-ip.heroku.com")
#conn.request("GET", "/")
#response = conn.getresponse()
#print(response.read())
while count <= counter: # co dziesiata liczba
# --------------- pierwsze wpisanie do bazy danych do Archive --------------------
with con:
cur = con.cursor()
cur.execute("UPDATE SANBROKER.Number_of_records SET Archive_num=%s",(count))
# ---------------------------------------------------------------------------------
if decrease == 0:
MatchPattern(count)
# Now I wanna check some expresions (2 or 3)
# After that i wanna write all the values into my database
#------- ostatnie czynności:
percentage = count / 100
print "rekordów: " + str(count) + " z: " + str(counter) + " procent dodanych: " + str(percentage) + "%"
with con:
cur = con.cursor()
cur.execute("UPDATE SANBROKER.Number_of_records SET Old_num=%s",(count))
decrease = 10-1
count +=1
else:
MatchPattern(count)
# Now I wanna check some expresions (2 or 3)
# After that i wanna write all the values into my database
# ------ ostatnie czynności:
percentage = count / 100
print "rekordów: " + str(count) + " z: " + str(counter) + " procent dodanych: " + str(percentage) + "%"
with con:
cur = con.cursor()
cur.execute("UPDATE SANBROKER.Number_of_records SET Old_num=%s",(count))
decrease -=1
count +=1
Well, I'm assuming check_reg is a function that returns a boolean (either True or False).
If that's the case, to check the return:
if expr1:
print "True."
else:
print "False"
There's more than one way to do it, but basically, if expr1: is all you need to do the checking.
To capture the return value of a function, assign the function to a name with an equal sign, like this:
return_value = somefunction(some_value)
print('The return value is ',return_value)
Keep in mind that when the first return statement is encountered, the function will exit. So if you have more than one return statement after each other, only the first will execute.
If you want to return multiple things, add them to a list and then return the list.
Here is an improved version of your function:
def match_pattern(count):
sock = urllib.urlopen(Link+str(count))
htmlsource = sock.read()
sock.close()
root = etree.HTML(htmlSource)
# root = etree.HTML(htmlSource) - duplicate line
# result = etree.tostring(root, pretty_print=True, method="html")
function_names = [check_reg, check_practice, no_ks, Registered_by, \
Name_doctor, Registration_no, PWZL, NIP, Spec, Start_date, \
Name_of_practise, TERYT, Street, House_no2, Flat_no, \
Post_code2, City2, Phone_no]
results = []
for function in function_names:
results.append(function(root))
return results
r = match_pattern(1)
print r[0] # this will be the result of check_reg(root)
The code you have posted is quite ambigous. Can you please fix the ident to let us know what belongs to the function and which part is the script.
A function can returns only one value. You cannot do :
return something
return something_else
return ...
The function will ends when first value will be returned.
What you can do is returning a list, tuple or dict containing all your values.
For instance :
return (something,something_else,...)
or
return [something,something_else,...]
In your case, it seems better to create a class that would have all values you want as attributes, and turn this function into a method that would set the attributes values.
class Example(object):
def __init__ ( self , link , count ):
sock = urllib.urlopen(link+str(count))
htmlSource = sock.read()
sock.close()
root = etree.HTML(htmlSource)
root = etree.HTML(htmlSource)
result = etree.tostring(root, pretty_print=True, method="html")
self.expr1 = check_reg(root)
self.expr2 = check_practice(root)
self.D_expr1 = no_ks(root)
...
self.D_expr8 = Start_date(root)
#-----Reg_practice-----
self.R_expr1 = Name_of_practise(root)
...
self.R_expr9 = Kind_of_practice(root)
#------Serv_practice -----
self.S_expr1 = TERYT2(root)
...
self.S_expr7 = Phone_no(root)
Then you will be able to use this class like :
exampleInstance = Example ( "link you want to use" , 4 ) # the second argument is your 'count' value
# Now you can use attributes of your class to get the values you want
print exampleInstance . expr1
print exampleInstance . S_expr7