2

I am having an issue trying to save data to MongoDB.

I first run this python program:

import pymongo
import sys

def main():
    connection = pymongo.Connection("mongodb://localhost", safe = True) 

    db = connection.m101
    people = db.people

    person = {'name':'Barack Obama', 'role':'president'}
    people.insert(person)

but then, when i try to retrieve the data from the mongoshell:

> use m101

switched to db m101

 > db.people.find()

returns nothing! I'm not sure what is going on. Thanks for your help.

3 Answers 3

4

Your code is not working because main() is never called.

Adding

if __name__ == '__main__':
    main()

will execute your defined main function when executed.

Sign up to request clarification or add additional context in comments.

1 Comment

To clarify: Python will execute the outermost scope (no indent level) when executing the file directly; as written in the question, the script just defines main without calling it. The __name__ == '__main__' predicate ensures that main is only executed if the script is executed directly (i.e. python my_main.py from a console); main will not be executed if this script is imported. Whether this is the desired behavior depends on your use case.
1

You are not executing your main() function so nothing was ever executed.

Comments

0

Simple solution

from flask import Flask
from flask_pymongo import PyMongo
import json
import datetime
import urllib, json
from flask import jsonify
from bson.json_util import dumps

@app.route("/saveBookings", methods=['POST'])
def saveBookings():
    posts = mongo.db.bookings

    post = {"meetingRoom_name": "kriti_jio",
          "personName": "honey",
         "meetingRoom_location": "kannauj",
         "book_start_time": datetime.datetime.utcnow()}
    post_id = posts.insert_one(post).inserted_id
    return  jsonify(status="done",id=dumps(post_id),action="Data saved Succesfully",error="false");

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.