(Pymongo) AttributeError: 'InsertManyResult' object has no attribute 'inserted_count' - python

I follow the manual https://api.mongodb.com/python/3.4.0/api/pymongo/results.html
and similar problem AttributeError: 'dict' object has no attribute 'is_active' (PyMongo And Flask) (not fit mine issue)
after successfully .insert_many or .insert_one,
the .inserted_count not working
function main part I stock
if one_or_many_bool == True:
x = mycol.insert_many(insert_values_json)
else:
x = mycol.insert_one(insert_values_json)
return x
print(x)
print(x.inserted_count, "documents insert.")
output:
<pymongo.results.InsertManyResult object at 0x0000017D1D256950>
Traceback (most recent call last):
File "C:\Users\chuan\OneDrive\Desktop\10.17_connect_mongoD_練習\fake02.py", line 54, in <module>
print(x.inserted_count, "documents inserted.")
AttributeError: 'InsertManyResult' object has no attribute 'inserted_count'
the whole code(incase someone want to take a look):
import pymongo
import datetime
import json
from bson.objectid import ObjectId
from bson import json_util
def init_db(ip, db, coll):
try:
myclient = pymongo.MongoClient('mongodb://' + ip + '/')
mydb = myclient[db]
mycol = mydb[coll]
except Exception as e:
msg_fail_reason = "error in init_db function"
return msg_fail_reason
return mydb, mycol
# ins_data = insert_db_data
# one_or_many_bool: input 1 means True; input 0 is False
def ins_data(one_or_many_bool, insert_values_json ):
try:
if one_or_many_bool:
x = mycol.insert_many(insert_values_json)
else:
x = mycol.insert_one(insert_values_json)
return x
except Exception as e:
msg_fail_reason = "error in ins_data function"
return msg_fail_reason
msg_fail_reason = "no error occur"
ip_input = input("Enter the ip: ")
exist_DB_name = input("Enter exist DB name: ")
exist_coll_name = input("Enter exist collection name: ")
mydb, mycol = init_db(ip_input, exist_DB_name, exist_coll_name)
update_one_or_many = input("U are update one or many values? (ex:1 for many , 0 for one): ")
newvalues_str = input("Enter new values: ")
one_or_many_bool = bool(int(update_one_or_many))
insert_values_json =json.loads(newvalues_str)
x = ins_data(one_or_many_bool, insert_values_json )
print(x)
print(x.inserted_count, "documents insert.")
number_of_insert_data = int(x.inserted_count)
modified_data_list = []
for modified_data in mycol.find().sort("_id", -1).limit(number_of_insert_data):
# print(modified_data)
modified_data_list.append(modified_data)
def parse_json(data):
return json.loads(json_util.dumps(data))
# if someone want data in json
modified_data_json = parse_json(modified_data_list)
# 1 means success
return_status_str = { "ok" : 1 , "msg" : msg_fail_reason , "count" : number_of_insert_data}
print(return_status_str)
print(type(return_status_str))

As the PyMongo doc described, InsertManyResult doesn't has the inserted_count attrbute. You can use len(result.inserted_ids) instead.

Related

Getting Array keys in POST method using POSTMAN in Python 3 Flask-Restful API

How to get the value of array in postman using parser = reqparse.RequestParser() in flask api?
Im getting an error says: NoneType' object is not subscriptable
And here is my code:
class CreateUser(Resource):
def post(self):
try:
conn = None
parser = reqparse.RequestParser()
parser.add_argument('username', type = str)
args = parser.parse_args()
name = args['username'][0]
return name
except Exception as e:
x = str(e)
x.replace('\n', '')
return {'status' : 'failed', 'message' : str(x)}
finally:
if conn is not None:
conn.close()
im getting error with this name = args['username'][0] and i also try to make this too name = args[0]['username'] and still error appears and when i just make this like name = args['username'] the postman replies null. please help me.
Use this
def post(self):
try:
conn = None
parser = reqparse.RequestParser()
parser.add_argument('username[0]', type = str)
parser.add_argument('username[1]', type = str)
args = parser.parse_args()
name = args['username[0]']
return name
except Exception as e:
x = str(e)
x.replace('\n', '')
return {'status' : 'failed', 'message' : str(x)}
finally:
if conn is not None:
conn.close()
Editing for multiple params
form data should be like this
username: "user1"
username: "user2"
username: "user3"
Yes you can pass multiple values with same key
def post(self):
try:
conn = None
parser = reqparse.RequestParser()
parser.add_argument('username', type = str, action='append')
args = parser.parse_args()
name = args['username']
print(name) # ['user1', 'user2','user3'] you can traverse over this list

Python access the Login directly without using With Function as Key :

Here is the complete code where i am trying to use ForexConnect().get_history(.... instead of fx.get_history( and i do not want this line of code "with ForexConnect() as fx:" how to achieve this ,the last section of code given produces excpetion issues .
Why i do not want to use "with ForexConnect() as fx:" The reason is once the session "with ForexConnect() as fx:" the function is logged out .My idea is to be in the session after once logged in .So i do not want to try this with "with ForexConnect() as fx:"
import argparse
import pandas as pd
from forexconnect import ForexConnect, fxcorepy
import common_samples
parser = False
def parse_args():
parser = argparse.ArgumentParser(description='Process command parameters.')
common_samples.add_main_arguments(parser)
common_samples.add_instrument_timeframe_arguments(parser)
common_samples.add_date_arguments(parser)
common_samples.add_max_bars_arguments(parser)
args = parser.parse_args()
return args
def main():
if parser == False :
#args = parse_args()
str_user_id = 'Dxxxx'
str_password = 'xxxxx'
str_url = "http://www.fxcorporate.com/Hosts.jsp"
str_connection = 'Demo'
str_session_id = 'None'
str_pin = 'None'
str_instrument = 'USOil'
str_timeframe = 'W1'
quotes_count = 5
date_from = None
date_to = None
else :
args = parse_args()
str_user_id = args.l
str_password = args.p
str_url = args.u
str_connection = args.c
str_session_id = args.session
str_pin = args.pin
str_instrument = args.i
str_timeframe = args.timeframe
quotes_count = args.quotescount
date_from = args.datefrom
date_to = args.dateto
with ForexConnect() as fx:
try:
fx.login(str_user_id, str_password, str_url,
str_connection, str_session_id, str_pin,
common_samples.session_status_changed)
print("")
print("Requesting a price history...")
print(str_instrument,str_timeframe,date_from,date_to,quotes_count)
history = fx.get_history(str_instrument, str_timeframe, date_from, date_to, quotes_count)
current_unit, _ = ForexConnect.parse_timeframe(str_timeframe)
date_format = '%d.%m.%Y %H:%M:%S'
print("print history ",history)
df = pd.DataFrame(history, columns=['Date', 'BidOpen', 'BidHigh','BidLow', 'BidClose', 'AskOpen', 'AskHigh', 'AskLow', 'AskClose', 'Volume'])
print(df)
if current_unit == fxcorepy.O2GTimeFrameUnit.TICK:
print("Date, Bid, Ask")
print(history.dtype.names)
for row in history:
print("{0:s}, {1:,.5f}, {2:,.5f}".format(
pd.to_datetime(str(row['Date'])).strftime(date_format), row['Bid'], row['Ask']))
else:
print("Date, BidOpen, BidHigh, BidLow, BidClose, Volume")
for row in history:
print("{0:s}, {1:,.5f}, {2:,.5f}, {3:,.5f}, {4:,.5f}, {5:d}".format(
pd.to_datetime(str(row['Date'])).strftime(date_format), row['BidOpen'], row['BidHigh'],
row['BidLow'], row['BidClose'], row['Volume']))
except Exception as e:
common_samples.print_exception(e)
try:
fx.logout()
except Exception as e:
common_samples.print_exception(e)
if __name__ == "__main__":
main()
print("")
input("Done! Press enter key to exit\n")
Here i want to login once and be in the logged in session forever.
With the below function this is working fine .But here the problem is once the With section is over the session is disconnected.
with ForexConnect() as fx:
try:
fx.login(str_user_id, str_password, str_url,
str_connection, str_session_id, str_pin,
common_samples.session_status_changed)
history = fx.get_history(str_instrument, str_timeframe, date_from, date_to, quotes_count)
current_unit, _ = ForexConnect.parse_timeframe(str_timeframe)
To stay in the session tried the below code without using the "With" and as :
Here the login is successful but could not get the data in history = ForexConnect().get_history
Error Code :
ForexConnect().login(str_user_id, str_password, str_url,
str_connection, str_session_id, str_pin,
common_samples.session_status_changed)
**history = ForexConnect().get_history(str_instrument, str_timeframe, date_from, date_to, quotes_count)**
How to make it the ** ** code work without any exception error without using With --- as : keyworkds.
what is the alternative for this with and as : why when i try to access as history = ForexConnect().get_history ( ... it is giving error how to overcome this issue.

Exception not raised assertRaises()?

I am giving a wrong input and I want an exception to be raised. Somehow this is not happening. This is my unit test code:
def test_invalid_bag_json_conversion_1(self):
file_name = "../test/test_files/wrong_bag.bag"
ru = RosbagUploader(file_name, self.json_output, "", "", "", "")
status = ru.start()
self.assertRaises(Exception, RosbagUploader, file_name, self.json_output, "", "", "", "")
self.assertEquals(ReturnCodes.FAIL, status)
and my code that I am testing:
class RosbagUploader(object):
"""
#brief Uploads deserialized input Rosbag file to ElasticSearch or
stores it locally
"""
def __init__(self, _rosbag_filepath, _json_filename, _es_addr, _es_index,
_es_type, _buffer_size):
self.overall_status = ReturnCodes.SUCCESS
self._rosbag_filepath = _rosbag_filepath
self._json_filename = _json_filename
self._buffer_size = _buffer_size if _buffer_size > 0 else 5000
self._es_type = _es_type
self._es_addr = _es_addr
self._es_index = _es_index
self._es_buff = []
try:
self._rosbag = rosbag.Bag(_rosbag_filepath, "r")
if self._es_addr:
self._es = Elasticsearch() if _es_addr == "" else \
Elasticsearch([_es_addr])
self._total_num_record = self._rosbag.get_message_count()
except:
print("[ERROR] {}".format(sys.exc_info()))
self.overall_status = ReturnCodes.FAIL
It shows the output that the exception is raised as below:
[ERROR] (<class 'rosbag.bag.ROSBagException'>, ROSBagException(), <traceback object at 0x7fdcb463e8c0>)
EException AttributeError: "'RosbagUploader' object has no attribute '_rosbag'" in <bound method RosbagUploader.__del__ of <rosbag_deserializer_core.RosbagUploader object at 0x7fdcb4899ad0>> ignored
Which is what it should do. But why doesnt it raise the exception?
You are essentially ignoring the exception since you are not re-raising after the print statement:
try:
[...]
except:
print("[ERROR] {}".format(sys.exc_info()))
self.overall_status = ReturnCodes.FAIL
You need to re-raise for callers to receive the exception:
try:
[...]
except:
print("[ERROR] {}".format(sys.exc_info()))
self.overall_status = ReturnCodes.FAIL
raise
Do you have a __del__ destruction method? Seems to be failing there.

Flask Python: Unable to get parameters using request.args

I want to request some parameters from a external web app. I create an API with flask and query data from MySQL. I able to query the data if I gave a fix input but not when using request.args. I try both request.args['name'] and request.args.get('name') but return the output of Exception path.
Below is my current code. I comment out the fix input I used.
from flask import Flask,jsonify,abort,make_response,request,render_template
import MySQLdb
import MySQLdb.cursors
#app.route('/KLSE/search', methods=['GET'])
def KLSEsearch():
db = MySQLdb.connect(host='vinus.mysql.pythonanywhere-services.com',user='vinus',passwd='Vindex2016',db='vinus$default',cursorclass=MySQLdb.cursors.DictCursor)
curs = db.cursor()
#name ='P'
#macd = 'H'
#volumeMin = '_'
#volumeMax = '_'
#stoch ='H1'
#bollinger ='H'
#rsi ='H1'
#atr ='LV'
#trade = 'HOLD'
#limit = 3
#offSet = 1
name = request.args.get('name')
volumeMin = request.args['volumeMin']
volumeMax = request.args['volumeMax']
macd = request.args['macd']
stoch = request.args['stoch']
bollinger = request.args['bollinger']
rsi = request.args['rsi']
atr = request.args['atr']
trade = request.args['trade']
limit = request.args['limit']
offSet = request.args['offSet']
query0 = "SELECT * FROM KLSE WHERE Stock LIKE '%s' AND"
#query1 = "(Vindex BETWEEN (IF(%s='_',-5000,%s)) AND (IF(%s='_',5000,%s))) AND "
query2 = "(Volume_changes_pc BETWEEN (IF (%s='_',-5000,%s)) AND (IF(%s='_',5000,%s))) AND "
query3 = "MACD LIKE %s AND "
query4 = "STOCH LIKE %s AND "
query5 = "BOLLINGER LIKE %s AND "
query6 = "RSI LIKE %s AND "
query7 = "ATR LIKE %s AND "
query8 = "TRADE LIKE %s LIMIT %s OFFSET %s"
query = query0+query2+query3+query4+query5+query6+query7+query8
input = name+"%",volumeMin,volumeMin,volumeMax,volumeMax,macd,stoch,bollinger,rsi,atr,trade,limit,offSet
try:
curs.execute(query,(input))
g = curs.fetchall()
except Exception:
return 'Error: unable to fetch items'
#return "hihi"
return jsonify({'Stock': g})
The output with fix value as below. I think it shows the query to MySQL is correct.
http://vinus.pythonanywhere.com/KLSE/search1
For the user input value, which use the args,
http://vinus.pythonanywhere.com/KLSE/search?atr=%&bollinger=%&macd=%&name=M&rsi=%&stoch=%&volumeMax=&volumeMin=&trade=HOLD&limit=5&offSet=1
What is the right way, get the parameters? volumeMin,volumeMax,limit and offSet are in float and integers.
You have to serialize your data first.
def serialize():
return {
"id" : g.id,
"volumeMin" : g.name,
"volumeMax" : g.address,
"macd" : g.city,
"stoch" : g.state,
"zipCode" : g.zipCode,
"bollinger" : g.bollinger,
}
#app.route("/KLSE/search/.json")
def stock_json():
query = your.db.query()
return jsonify(Stock=[i.serialize for i in query])

TypeError: 'NoneType' object is not subscriptable in Python

I get this error and I don't know what the problem is.
Code:
__author__ = 'victor'
import requests
import xmltodict
url = 'http://webservices.ns.nl/ns-api-storingen?station=UT'
user = 'victor_shao#hotmail.com'
passw = 'dMHAg67WACsUdrQmqctr3giaTpTnsJmhPP2EcQWlVnMw3zmHXvSE-A'
response = requests.get(url, auth=(user, passw))
xmldi = xmltodict.parse(response.text)
storing = 0
allestoringen = 4
print("Storingen",'\n','ongeplande storingen')
print('{0:15s}'.format('id'),'{0:40s}'.format('traject'),'{0:20s}'.format('reden'),'{0:100s}'.format('bericht'),'{0:25s}'.format('datum'))
for storing in range(0, allestoringen):
id = xmldi['Storingen']['Ongepland']['Storing']['id']
traject = xmldi['Storingen']['Ongepland']['Storing']['Traject']
reden = xmldi['Storingen']['Ongepland']['Storing']['Reden']
bericht = xmldi['Storingen']['Ongepland']['Storing']['Bericht']
datum = xmldi['Storingen']['Ongepland']["Storing"]['Datum']
print("Geplande storingen ")
print('{0:25s)'.format('id'),'{0:40s}'.format('traject'),'{0:35s}'.format('periode'),'{0:200s}'.format('advies'),'{0:250s}'.format('bericht'),'{0:50s}'.format('oorzaak'),'{0:30s}'.format('vertraging'))
for storing in range(0, allestoringen):
id = xmldi['Storingen']['Gepland']['Storing']['id']
traject = xmldi['Storingen']['Gepland']['Storing']['Traject']
periode = xmldi['Storingen']['Gepland']['Storing']['Periode']
advies = xmldi['Storingen']['Gepland']['Storing']['Advies']
bericht = xmldi['Storingen']['Gepland']['Storing']['Bericht']
oorzaak = xmldi['Storingen']['Gepland']['Storing']['Oorzaak']
vertraging = xmldi['Storingen']['Gepland']['Storing']['Vertraging']
Here is the output, where I should fill in the information:
C:\Python34\python.exe C:/Users/avi/PycharmProjects/untitled1/storing.py Storingen
ongeplande storingen id traject
reden bericht
datum Traceback (most recent call last): File
"C:/Users/avi/PycharmProjects/untitled1/storing.py", line 18, in
id = xmldi['Storingen']['Ongepland']['Storing']['id'] TypeError: 'NoneType' object is not subscriptable
Process finished with exit code 1
How can I fix this? I would appreciate any help.
Since xmldi['Storingen']['Ongepland'] has the value None
id = xmldi['Storingen']['Ongepland']['Storing']['id']
should be changed to:
id = xmldi['Storingen']['Gepland']['Storing']['id']

Categories