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.
Related
I am trying to get the following MWE to work, however I get the following error:
words = getWords(sys.argv[1].decode(sys.stdin.encoding)) AttributeError: 'str' object has no attribute 'decode'
If I remove the decode part as suggested in other questions, it will throw a syntax error for
if words:
^
SyntaxError: invalid syntax
I am uncertain as how to fix this in order to be able to receive the requested results.
Could anyone help me out here?
Thank you and sorry for the question!
#!/usr/bin/env python
# encoding: utf-8
import sys
import sqlite3
from collections import namedtuple
conn = sqlite3.connect("wnjpn.db")
Word = namedtuple('Word', 'wordid lang lemma pron pos')
def getWords(lemma):
cur = conn.execute("select * from word where lemma=?", (lemma,))
return [Word(*row) for row in cur]
def getWord(wordid):
cur = conn.execute("select * from word where wordid=?", (wordid,))
return Word(*cur.fetchone())
Sense = namedtuple('Sense', 'synset wordid lang rank lexid freq src')
def getSenses(word):
cur = conn.execute("select * from sense where wordid=?", (word.wordid,))
return [Sense(*row) for row in cur]
def getSense(synset, lang='jpn'):
cur = conn.execute("select * from sense where synset=? and lang=?",
(synset,lang))
row = cur.fetchone()
return row and Sense(*row) or None
Synset = namedtuple('Synset', 'synset pos name src')
def getSynset(synset):
cur = conn.execute("select * from synset where synset=?", (synset,))
return Synset(*cur.fetchone())
SynLink = namedtuple('SynLink', 'synset1 synset2 link src')
def getSynLinks(sense, link):
cur = conn.execute("select * from synlink where synset1=? and link=?",
(sense.synset, link))
return [SynLink(*row) for row in cur]
def getSynLinksRecursive(senses, link, lang='jpn', _depth=0):
for sense in senses:
synLinks = getSynLinks(sense, link)
if synLinks:
print( ''.join([' '*2*_depth,
getWord(sense.wordid).lemma,
' ',
getSynset(sense.synset).name]))
_senses = []
for synLink in synLinks:
sense = getSense(synLink.synset2, lang)
if sense:
_senses.append(sense)
getSynLinksRecursive(_senses, link, lang, _depth+1)
def getWordsFromSynset(synset, lang):
cur = conn.execute("select word.* from sense, word where synset=? and word.lang=? and sense.wordid = word.wordid;", (synset,lang))
return [Word(*row) for row in cur]
def getWordsFromSenses(sense, lang):
for s in sense:
print( getSynset(s.synset).name)
syns = getWordsFromSynset(s.synset, lang)
for sy in syns:
print( ' ' + sy.lemma)
if __name__ == '__main__':
if len(sys.argv)>=3:
words = getWords(sys.argv[1].decode(sys.stdin.encoding))
if words:
for w in words:
sense = getSenses(w)
link = len(sys.argv)>=3 and sys.argv[2] or 'hypo'
lang = len(sys.argv)==4 and sys.argv[3] or 'jpn'
if link == 'syns':
getWordsFromSenses(sense, lang)
else:
getSynLinksRecursive(sense, link, lang)
else:
print >>sys.stderr, "(nothing found)"
else:
print("usage: python jpWordnet.py ピラミッド syns")
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
I am working on a python script to add a VM to a DRS group.
Here is a powershell script that is doing the job. How to translate it to py?
$spec = New-Object VMware.Vim.ClusterConfigSpecEx
$spec.groupSpec = New-Object VMware.Vim.ClusterGroupSpec[] (1)
$spec.groupSpec[0] = New-Object VMware.Vim.ClusterGroupSpec
$spec.groupSpec[0].operation = "edit"
$spec.groupSpec[0].info = $DrsGroup
$spec.groupSpec[0].info.vm += $VM.ExtensionData.MoRef
$Cluster.ExtensionData.ReconfigureComputeResource_Task($spec, $true)
actually I block on the last line becuase I do not found the ReconfigureComputeResource methode. My code hereafter:
def get_drsgroup(self, cluster_obj=None, group_name=None):
if cluster_obj is None:
cluster_obj = self.cluster_obj
if group_name:
group_list = [group for group in cluster_obj.configurationEx.group if group.name == group_name]
if group_list:
return group_list[0]
return None
def assign_vm_to_group(self):
drs_group = self.get_drsgroup(group_name="DC_VM")
my_vm = self.get_obj(
[vim.VirtualMachine],
"Test_vm",
return_all=True)
spec = vim.cluster.ConfigSpecEx()
groupspec = vim.cluster.GroupSpec()
groupspec.operation = "edit"
groupspec.info = drs_group
groupspec.info.vm += my_vm
self.cluster_obj.xxxxxxxxxxxxxx
Thanks for your help
def manage_vm_to_DRS_group(self, action=None):
#--- requiered objects already exist
drs_group = self.get_drsgroup(group_name=self.drs_rule_name)
my_vm = self.get_obj(
[vim.VirtualMachine],
self.vm,
return_all=True
)
#---
try:
spec = vim.cluster.ConfigSpecEx()
my_groupSpec = vim.cluster.GroupSpec()
my_groupSpec.operation = "edit"
my_groupSpec.info = drs_group
if self.state == 'present':
my_groupSpec.info.vm += my_vm
elif self.state == 'removed':
#my_groupSpec.info.vm = my_groupSpec.info.vm.remove(my_vm[0])
my_groupSpec.info.vm.remove(my_vm[0])
else:
self.module.fail_json(msg="Module failure: check module, fuction: assign_vm_to_group, indice: 1")
spec.groupSpec.append(my_groupSpec)
if not self.check_mode:
self.cluster_obj.ReconfigureComputeResource_Task(spec, modify=True)
except:
self.module.fail_json(msg="Module failure:Failed to assign vm '%s' to DRS group '%s'" % (
self.vm, self.drs_rule_name))
self.module.exit_json(changed=True, result="SUCCESS vm '%s' is '%s' on DRS group '%s'" % (
self.vm, self.state, self.drs_rule_name))
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