Im trying to add a movie to my mongo DB table but it is only included the last value could someone tell me where I am going wring the code I am using in my python file is below:
#app.route('/insert_movie', methods=['POST'])
def insert_movie():
movie_added = {'title': request.form.get('title')}
{'imdb.rating': request.form.get('imdb.rating')}
{'tomato.rating': request.form.get('tomato.rating')}
{'year': request.form.get('year')}
{'runtime': request.form.get('runtime')}
{'actors': request.form.get('actors')}
{'director': request.form.get('director')}
{'plot': request.form.get('plot')}
mongo.db.movie_information.insert_one(movie_added)
return redirect(url_for('get_movies'))
Try putting all of the fields into a single object (see below). That way, when you insert one movie, that movie contains all of the fields from the one object that you sent.
movie_added = {'title': request.form.get('title'),
'imdb.rating': request.form.get('imdb.rating'),
'tomato.rating': request.form.get('tomato.rating'),
'year': request.form.get('year'),
'runtime': request.form.get('runtime'),
'actors': request.form.get('actors'),
'director': request.form.get('director'),
'plot': request.form.get('plot')}
mongo.db.movie_information.insert_one(movie_added)
return redirect(url_for('get_movies'))`
Related
I'm writing a python program to save and retrieve a customer data in cloud datastore. My entity looks like below:
entity.update({
'customerId': args['customerId'],
'name': args['name'],
'email': args['email'],
'city': args['city'],
'mobile': args['mobile']
})
datastore_client.put(entity)
I'm successfully saving the data. Now, I want to retrieve a random email id from the a record. I have written the below code:
def get_customer():
query = datastore_client.query(kind='CustomerKind')
results = list(query.fetch())
chosen_customer = random.choice(results)
print(chosen_customer)
But instead getting only one random email id, I'm getting the entire row like this:
<Entity('CustomerKind', 6206716152643584) {'customerId': '103', 'city': 'bhubaneswar', 'name': 'Amit', 'email': 'amit#gmail.com', 'mobile': '7879546732'}>
Can anyone suggest how can I get only 'email': 'amit#gmail.com' ? I'm new to datastore.
When using
query = datastore_client.query(kind='CustomerKind')
results = list(query.fetch())
you are retrieving all the properties from all the entities that will be returned.
Instead, you can use a projection query, which allows you to retrieve only the specified properties from the entities:
query = client.query(kind="CustomerKind")
query.projection = ["email"]
results = list(query.fetch())
Using projection queries is recommended for cases like this, in which you only need some properties as they reduce cost and latency.
I got a list in Python with Twitter user information and exported it with Pandas to an Excel file.
One row is one Twitter user with nearly all information of the user (name, #-tag, location etc.)
Here is my code to create the list and fill it with the user data:
def get_usernames(userids, api):
fullusers = []
u_count = len(userids)
try:
for i in range(int(u_count/100) + 1):
end_loc = min((i + 1) * 100, u_count)
fullusers.extend(
api.lookup_users(user_ids=userids[i * 100:end_loc])
)
print('\n' + 'Done! We found ' + str(len(fullusers)) + ' follower in total for this account.' + '\n')
return fullusers
except:
import traceback
traceback.print_exc()
print ('Something went wrong, quitting...')
The only problem is that every row is in JSON object and therefore one long comma-seperated string. I would like to create headers (no problem with Pandas) and only write parts of the string (i.e. ID or name) to colums.
Here is an example of a row from my output.xlsx:
User(_api=<tweepy.api.API object at 0x16898928>, _json={'id': 12345, 'id_str': '12345', 'name': 'Jane Doe', 'screen_name': 'jdoe', 'location': 'Nirvana, NI', 'description': 'Just some random descrition')
I have two ideas, but I don't know how to realize them due to my lack of skills and experience with Python.
Create a loop which saves certain parts ('id','name' etc.) from the JSON-string in colums.
Cut off the User(_api=<tweepy.api. API object at 0x16898928>, _json={ at the beginning and ) at the end, so that I may export they file as CSV.
Could anyone help me out with one of my two solutions or suggest a "simple" way to do this?
fyi: I want to do this to gather data for my thesis.
Try the python json library:
import json
jsonstring = "{'id': 12345, 'id_str': '12345', 'name': 'Jane Doe', 'screen_name': 'jdoe', 'location': 'Nirvana, NI', 'description': 'Just some random descrition')"
jsondict = json.loads(jsonstring)
# type(jsondict) == dictionary
Now you can just extract the data you want from it:
id = jsondict["id"]
name = jsondict["name"]
newdict = {"id":id,"name":name}
I'm trying to get some POST requests using Postman to MongoDb and everything works well.
Following is the code:
def add_npo():
add_new_npo = mongo.db.npos
name = request.json['name']
description = request.json['description']
category = request.json['category']
status = request.json["status"]
npo_id = add_new_npo.insert({'name': name, 'description':
description, 'category': category,'status': status})
new_npo = add_new_npo.find_one({'_id': npo_id })
output = {'name': new_npo["name"], 'description':
new_npo["description"], 'category': new_npo["category"], 'status':
new_npo["status"]}
return jsonify({'result' : output})
But how can I add new fields on the document without assigning them in advance?
You can add new fields on the document by update operation.
For example,
db.col.update({your filter}, {"$set": {"newField": newFieldValue}})
I am pretty new to using both SQLALCHEMY and the PYRAMID web framework. I am struggling with what might be a simple fix to some, but I haven't been able to figure it out. I have looked at some posts here on Stacks, but they don't quite answer my issue.
I have a many-to-many relationship in my database table. I am trying to return an object (categories) from the parent table assessment. I am trying at the moment to: return {'name': assessment.name, 'text': assessment.text, 'user': assessment.user_id, 'video':assessment.video_id, 'categories': assessment.categories.assessment_category_link} but this doesn't work --> 'categories': assessment.categories.assessment_category_link
I am able to return all the objects except categories. Below is the relevant error and code.
TRACEBACK:
line 306, in get_assessment
return {'name': assessment.name, 'text': assessment.text, 'user': assessment.user_id, 'video':assessment.video_id, 'categories': assessment.categories.assessment_category_link}
AttributeError: 'InstrumentedList' object has no attribute 'assessment_category_link'
SQLALCHEMY TABLE/RELATIONSHIP:
# MANY-to-MANY
association_table = Table('assessment_category_link', Base.metadata,
Column('assessment_id', Integer, ForeignKey('assessments.assessment_id')),
Column('category_id', Integer, ForeignKey('categories.category_id')))
class Assessment(Base):
# column/entity code
categories = relationship('Category', secondary='assessment_category_link', backref='assessments')
def __init__(self, name, text, user, video, categories):
# CODE
self.categories = categories
The GET() method, specifically the return value that is throwing the error:
#view_config(route_name='assessment', request_method='GET', renderer='json')
def get_assessment(request):
with transaction.manager:
assessment_id = int(request.matchdict['id'])
assessment = api.retrieve_assessment(assessment_id)
if not assessment:
raise HTTPNotFound()
return {'name': assessment.name, 'text': assessment.text, 'user': assessment.user_id, 'video':assessment.video_id, 'categories': assessment.categories.assessment_category_link}
I am not sure what you are trying to achieve since assessment.categories would return a list of Category objects that you need to iterate over. It is logical for such a list not to have an attribute named assessment_category_link (as the exception tells you), and it is not clear to me why you would want to access the association object anyway!
The relationship with the secondary keyword argument is meant to hide this complexity away so that assessment.categories would transparently return the list that you're after.
you can represent the categories list as you like, a suggestion for your case:
{...., 'categories': ', '.join([str(i) for i in assessment.categories])}
The answer above was very close, but the working code is:
{...., 'categories': ','.join([str(i) for i in assessment.categories])}
As suggested by similar Stack question/answer to the same issue: TypeError: sequence item 0: expected string, int found
I have a dictionary like this one:
{'company_name': 'Google', 'title': 'headline', ...}
I know that i can store the values using this way:
user = User(company_name=data_db_form['company_name'], title=data_db_form['title']...)
However this is not good if I have many form fields.
There is any way to do this without hard code all the maps? The key value of the dictionary is the same of his model.
You can use the following:
user = User(**data_db_form)
Here is the full example:
class User():
def __init__(self, company_name='unknown', title='unknown'):
self.company_name = company_name
self.title = title
data_db_form = {'company_name': 'Google', 'title': 'headline'}
user = User(**data_db_form)
print user.company_name # prints Google
print user.title # prints headline
Loop over the dictionary using for key, value in dic.iteritems():, then in each iteration you have company_name, title, etc. in key and Google, headline, etc. in value.