access last data added into json file - python

here I am creating a new customer and save it into a customers.json file
new_user = appregister.newDocument('customers', username_1)
new_user.set('username', username_1)
new_user.set('email', email)
new_user.save()
new_user = format_customers()
print(new_user)
body_json = json.dumps(new_user)
scriptuser = util.get_app_parameter("scriptuser", "beta")
username = scriptuser["username"]
password = scriptuser["password"]
url = 'https://****.***.**/*****-****-1-0/****-****/customers.json'
headers = {'Content-Type': 'application/json'}
new_items = new_user
body_json = json.dumps(new_items)
status, headers, data = network.request(url, method='PUT',
headers=headers,
body=body_json,
encoding='UTF-8',
username=username,
password=password)
here I want to send a mail to the customer(like when i register a new customer so the customer get an email with some random code) I don't think that I am accessing the customer email
sources = ["customers.json"]
for source in sources:
data = util.get_data_item(source)
if data is None or len(data) == 0:
continue
register = json.loads(data)
for json_obj in register['customers']:
try:
emailaddress = json_obj['email']
print(email) # I get NONE here
except Exception as e:
emailaddress = None
if emailaddress:
if email == json_obj['email'].lower().strip():
code = "".join( [random.choice(string.digits) for i in xrange(6)] )
HTML = util.get_data_item("send_code2.html")
subject = (app_properties.get(EMAIL_TITLE_KEY))
try:
messageText = 'Your code is : '+ code
except Exception, e:
response = {'status' : 'error', 'message' : str(e)}
return json.dumps(response), responseHeaders, 400
p = Properties()
p.load(StringReader(util.get_data_item('messages.properties')))
title = (p.getProperty('email.title', ''))
color = json.loads(util.get_data_item('theme.json'))['colors']['tint'][-6:]
imagedata = base64.b64encode(util.get_data_item_bytes('logo.png'))
messageHtml = Environment().from_string(HTML).render(code=code, title=title, color=color, imagedata=imagedata)
try:
sendEmail('no-reply#ggg.com', email, subject, messageHtml, messageText)
except Exception, e:
logger.error("ERROR " + str(e))
response = {'status' : 'error', 'message' : str(e)}
return json.dumps(response), responseHeaders, 400
appRegister.put('activationcode', code);
appRegister.put('state', 'pending')
appRegister.put('activationtries', '0')
appRegister.put('email', email)
return json.dumps({}), responseHeaders, 200
error = {'title': app_properties[REGISTRATION_ERROR_TITLE_KEY], 'message' : app_properties[REGISTRATION_ERROR_KEY]}
return "200", responseHeaders
this is how my customers.json file looks like
{
"customers": {
"Osar": {
"email": "gmail#gmail.com"
},
"eeforetzr": {
"email": "email1#hotmail.com"
},
"aaxel": {
"email": "hotmail#hotmail.com"
}
"Mark": {
"email": "mark#gmail.com"
}
}
}

Related

How to create reports with Python SDK Api

I am trying to create reports with Python on dailymotion but I have error,According to my received error, renponse is empty. I don't get it. I guess, My user coudln't login to dailymotion. Please check error.
{'data': {'askPartnerReportFile': None}, 'errors': [{'message': 'Not authorized to access `askPartnerReportFile` field.', 'path': ['askPartnerReportFile'], 'locations': [{'line': 3, 'column': 9}], **'type': 'not_authorized**'}]}
Traceback (most recent call last):
File "get_reports.py", line 143, in <module>
product='CONTENT',
File "get_reports.py", line 65, in create_report_request
return response.json()['data']['askPartnerReportFile']['reportFile']['reportToken'];
TypeError: 'NoneType' object is not subscriptable
Here is my code;
`
def get_access_token(app_key, app_secret, username, password):
'''
Authenticate on the API in order to get an access token
'''
response = requests.post('https://graphql.api.dailymotion.com/oauth/token', data={
'client_id': app_key,
'client_secret': app_secret,
'username': username,
'password': password,
'grant_type': 'password',
'version': '2'
})
if response.status_code != 200 or not 'access_token' in response.json():
raise Exception('Invalid authentication response')
return response.json()['access_token']
def create_report_request(access_token, dimensions, metrics, start_date, end_date, product, filters = None):
'''
Creating a report request
'''
reportRequest = """
mutation ($input: AskPartnerReportFileInput!) {
askPartnerReportFile(input: $input) {
reportFile {
reportToken
}
}
}
"""
response = requests.post(
'https://graphql.api.dailymotion.com',
json={
'query': reportRequest,
'variables': {
'input': {
'metrics': metrics,
'dimensions': dimensions,
'filters': filters,
'startDate': start_date,
'endDate': end_date,
'product': product,
}
}
},
headers={'Authorization': 'Bearer ' + access_token}
)
print(response.status_code)
if response.status_code != 200 or not 'data' in response.json():
raise Exception('Invalid response')
print(response.json())
return response.json()['data']['askPartnerReportFile']['reportFile']['reportToken'];
def check_report_status(access_token, report_token):
'''
Checking the status of the reporting request
'''
report_request_status_check = """
query PartnerGetReportFile ($reportToken: String!) {
partner {
reportFile(reportToken: $reportToken) {
status
downloadLinks {
edges {
node {
link
}
}
}
}
}
}
"""
response = requests.post(
'https://graphql.api.dailymotion.com',
json={
'query': report_request_status_check,
'variables': {
'reportToken': report_token
}
},
headers={'Authorization': 'Bearer ' + access_token}
)
if response.status_code != 200 or not 'data' in response.json():
raise Exception('Invalid response')
status = response.json()['data']['partner']['reportFile']['status'];
if (status == 'FINISHED'):
download_links = []
for url in map(lambda edge: edge['node']['link'], response.json()['data']['partner']['reportFile']['downloadLinks']['edges']):
download_links.append(url)
return download_links
else:
return None
def download_report(download_links, base_path=None):
'''
Downloading the report files
'''
cpt = 1
if not base_path:
base_path = os.getcwd()
for url in download_links:
r = requests.get(url)
filename = 'report_{}.csv'.format(cpt)
file_path = os.path.join(base_path, filename)
open(file_path, 'wb').write(r.content)
print('Report file {} downloaded: {}'.format(cpt, file_path))
cpt += 1
print('Generating access token...')
access_token = get_access_token(
app_key='******',
app_secret='*******',
username='*****',
password='*****'
)
print('Creating report request...')
report_token = create_report_request(
access_token=access_token,
dimensions=('DAY', 'VIDEO_TITLE'),
metrics=('VIEWS'),
filters={'videoOwnerChannelSlug': 'B******'},
start_date='2022-11-23',
end_date='2022-11-24',
product='CONTENT',
)
download_links = None
while not download_links:
print('Checking report status...')
# Checks every 15secs the report status
time.sleep(15)
download_links = check_report_status(
access_token=access_token,
report_token=report_token
)
download_report(download_links=download_links)
`
I tried to get data dailymotion api.
Thanks
This feature requires a specific API access, which is missing on your API Key, that's why you get the message Not authorized to access askPartnerReportFile field.
As it's a feature restricted to verified-partners, you should reach out to your content manager to ask him this kind of access, or you can try to contact our support

Getting error "400 Bad Request: The browser (or proxy) sent a request that this server could not understand." while accessing the below method

#endpoints.route('/login', methods=['POST'])
def login():
resp = {}
try:
users = user_collection
# login_user = users.find_one({'username': request.form['name']})
login_user = users.find({'username': request.form['username']})
if login_user:
if (request.form['password'] == login_user['password']):
session['username'] = request.form['username']
# return True
print("User logged in Successfully.")
print("Invalid username/password combination")
# return 'Invalid username/password combination'
status = {
"statusCode": "200",
"statusMessage": "User logged in Successfully."
}
except Exception as e:
print(e)
status = {
"statusCode": "400",
"statusMessage": str(e)
}
resp["status"] = status
return resp
I tried to submit POST request with JSON input from POSTMAN and expected the below response to be populated in POSTMAN response pane.
"statusCode": "200",
"statusMessage": "User logged in Successfully."

Problems with Django Template and Json Data

I get Expecting value: line 1 column 1 (char 0) error on the page when my cart is empty but works when cart is populated. I'm expecting the error but that doesn't help either. Same continues on the other template also if data is empty. Maybe it has to do something not being returned.
def cartdetails(request):
if request.session.get('token', None) != None:
tokenid = request.session.get("token")
headers = {'Authorization': 'token ' + str(tokenid[0])}
url = 'https://api-ecommerce.datavivservers.in/mobile_api/CartDetails/'
jsondata = requests.get(url, headers=headers).json()
print(jsondata)
try:
return render(request, 'cart.html', {
"order_id": jsondata['order_id'],
"user_id": jsondata['user_id'],
"wallet_amount": jsondata['wallet_amount'],
"payable_amount": jsondata['payable_amount'],
"payment_status": jsondata['payment_status'],
"payment_mode": jsondata['payment_mode'],
"order_status": jsondata['order_status'],
"delivery_status": jsondata['delivery_status'],
"order_delivery_type": jsondata['order_delivery_type'],
"get_cart_total_discount": jsondata['get_cart_total_discount'],
"get_cart_total_GST": jsondata['get_cart_total_GST'],
"get_cart_total": jsondata['get_cart_total'],
"get_cart_sub_total": jsondata['get_cart_sub_total'],
"get_cart_quantities": jsondata['get_cart_quantities'],
"get_cart_items": jsondata['get_cart_items'],
"deliveryCharges": jsondata['deliveryCharges'],
"subscription_type": jsondata['subscription_type'],
"subscriptionId": jsondata['subscriptionId'],
"products": jsondata['products']
})
except simplejson.errors.JSONDecodeError:
return render(request, 'cart.html', {})
else:
print("login")
return redirect('login')

How to get message from E11000 DuplicationKeyError?

So I am writing unittests for a project and I am testing register() function.
Here is it:
def register():
# Get information about user
username = request.get_json().get("username")
password = request.get_json().get("password")
name = request.get_json().get("name")
email = request.get_json().get("email")
# Put information about user in a tuple
values = (
None,
username,
User.hash_password(password),
name,
email,
None
)
try:
# Create user and update session
User(*values).create()
ActiveUser.logged_in = True
ActiveUser.username = username
info_log.info("User %s registered successfully." % username)
return jsonify(success=True, message="Registration successful!")
except pymongo.errors.DuplicateKeyError as e:
# Catch pymongo exception
return jsonify(success=False, message="Duplicated username or email!"), 403
I want to have three tests: valid, invalid (duplicate username), invalid (duplicate email).
# Register helper function
def register(self, username, password, name, email):
return self.app.post(
"/register",
data = json.dumps(dict(username = username, password = password, name = name, email = email)),
content_type='application/json',
follow_redirects = True
)
def test_02_valid_user_registration(self):
response = self.register('test', '12345678', 'Tester 1', 'test#mail.mail')
self.assertEqual(response.status_code, 200)
self.assertIn(b'Registration successful!', response.data)
def test_03_invalid_user_registration_duplicate_username(self):
response = self.register('test', '12345678', 'Tester 2', 'test1#mail.mail')
self.assertEqual(response.status_code, 403)
self.assertIn(b'Duplicate username or email!', response.data)
def test_04_invalid_user_registration_duplicate_email(self):
response = self.register('test2', '12345678', 'Tester 3', 'test#mail.mail')
self.assertEqual(response.status_code, 403)
self.assertIn(b'Duplicate username or email!', response.data)
As expected I get DuplicateKeyError, because I have set Unique for those parameters in the database.
pymongo.errors.DuplicateKeyError: E11000 duplicate key error collection: user.users index: username_1 dup key: { username: "test" }
Is there a way to get which is the duplicated item from the DuplicateKeyError, so I can have separate unit tests for duplicate username and email?
I know this is more of a component/integration testing rather than unit testing, but this is the only way I know how to do it in Python 3.
So I started digging through the implementation of DuplicateKeyError and I found that it contains code and details.
I printed the details of the error and got this:
{
"message": {
"code": 11000,
"errmsg": "E11000 duplicate key error collection: user.users index: username_1 dup key: {
username: \"test\"
}",
"index": 0,
"keyPattern": {
"username": 1
},
"keyValue": {
"username": "test"
}
},
"success": false
}
After that it was easy to get the two tests to work.
try:
# code
except pymongo.errors.DuplicateKeyError as e:
# Catch pymongo exception
key = list(e.details.get("keyValue").keys())[0]
value = e.details.get("keyValue").get(key)
return jsonify(success=False, message="Duplicate %s: %s" % (key, value)), 403
And the tests:
def test_03_invalid_user_registration_duplicate_username(self):
response = self.register("test", "12345678", "Tester 2", "test1#mail.mail")
self.assertEqual(response.status_code, 403)
self.assertIn(b"Duplicate username: test", response.data)
def test_04_invalid_user_registration_duplicate_email(self):
response = self.register("test", "12345678", "Tester 3", "test#mail.mail")
self.assertEqual(response.status_code, 403)
self.assertIn(b"Duplicate email: test#mail.mail", response.data)

Successfully created a tokbox project, using python and urllib2, however I cannot create S3-archive

Using python/urllib2 I've successfully created a tokbox/opentok project.
However I am unable to create the much-needed S3-archive. When attempted to get the S3-part working, I'm receiving the following:
403, Forbidden
{"code":-1,"message":"Invalid token","description":"Invalid token"}
I'm using jwt.encode to create the needed token, using ist:account.
Though for the S3 portion, I also tried ist:project.
When using the put-call, I've tried the original token, used for creating the original project, as well as a newly created token, (both account or project)...but I still see the "Invalid token" message.
token = jwt.encode({"iss": "*******",
"iat": int(time.time()),
"exp": int(time.time()) + 180,
"ist": "account",
"jti": str(uuid.uuid4())},
'***************************************',
algorithm='HS256')
url = 'https://api.opentok.com/v2/project'
headers = { "X-OPENTOK-AUTH": token }
values = {'name' : 'MyTestproject' }
data = json.dumps(values)
req = urllib2.Request(url, data, { 'X-OPENTOK-AUTH': token, 'Content-Type': 'application/json'})
try:
f = urllib2.urlopen(req)
except urllib2.URLError as e:
print e.reason
print e.code
print e.read()
sys.exit()
jsondump = json.loads(f.read())
api_key = jsondump['apiKey']
s3_token = jwt.encode({"iss": "*******",
"iat": int(time.time()),
"exp": int(time.time()) + 180,
"ist": "account",
"jti": str(uuid.uuid4())},
'***************************************',
algorithm='HS256')
s3_data = json.dumps( {
"type": "s3",
"config": {
"accessKey":s3_access_key,
"secretKey":s3_secret_key,
"bucket": s3_prod_bucket
},
"fallback":"opentok"
})
s3_url = 'https://api.opentok.com/v2/project/'+ api_key + '/archive/storage'
#s3_req = urllib2.Request(s3_url, s3_data, { 'X-OPENTOK-AUTH': token, 'Content-Type': 'application/json'})
s3_req = urllib2.Request(s3_url, s3_data, { 'X-OPENTOK-AUTH': s3_token, 'Content-Type': 'application/json'})
s3_req.get_method = lambda: 'PUT'
try:
f = urllib2.urlopen(s3_req)
except urllib2.URLError as e:
print e.reason
print e.code
print e.read()
sys.exit()
Expected result is to have the S3-Archive set within the tokbox project.
According to the documentation in [1], the token to do REST API requests must be in the following format:
{
"iss": "your_api_key",
"ist": "project",
"iat": current_timestamp_in_seconds,
"exp": expire_timestamp_in_seconds,
"jti": "jwt_nonce"
}
[1] https://tokbox.com/developer/rest/#authentication

Categories