convert pymongo cursor to json - pymongo

I know this is a fairly common problem. I'm writing a small Flask app and I'm trying to feed some queries back to the view.
I've connected to my local MongoDB setup, and made a successful query - but I can't generate a json object with it.
The most common solution I've seen is to import json_util from pymongo i.e.
import json
from pymongo import json_util
results = connection.get_collection('papayas_papaya')
results = results.find({
'identifier': '1',
})
serialized_results = [json.dumps(result, default=json_util.default, separators=(',', ':')) for result in results]
I've installed pymongo into my Flask virtualenv using pip i.e :
pip install pymongo
When running the above code I keep getting the following error:
ImportError: cannot import name json_util
I can see this line in the pymongo-2.3-py2.6.egg-info/installed-files.txt
../bson/json_util.py
Anyone got any tips that can help me figure out what I'm doing wrong?
UPDATE:
Having noodled about with this a little further - I've managed to get this working thus:
import pymongo
from bson.json_util import dumps
connection = pymongo.Connection("localhost", 27017)
db = connection.mydocs
def get():
cursor = db.foo.find({"name" : "bar"})
return dumps(cursor)
One of the problems I had was trying to pip install bson independently - pymongo brings bson with it and importing bson separately caused problems.
Thanks #Cagex for pointing me in the right direction

It looks like you want to import from bson not pymongo. I believe json_util was moved to that module recently.
https://pymongo.readthedocs.io/en/stable/api/bson/json_util.html

I've seen quite a few posts on this issue but they didn't resolve the issue for me. What worked for me was using dumps(), then loads():
import pymongo
from bson.json_util import dumps
from bson.json_util import loads
connection = pymongo.Connection("localhost", 27017)
db = connection.mydocs
def get():
cursor = db.foo.find({"name" : "bar"})
return loads(dumps(cursor))

you can use list() to convert pymongo cursor to json object.
import pymongo
from bson.json_util import dumps
from bson.json_util import loads
connection = pymongo.Connection("localhost", 27017)
db = connection.mydocs
def get():
cursor = list(db.foo.find({"name" : "bar"}))
return loads(dumps(cursor))

You first need define your own JSONEncoder:
import json
from datetime import datetime
from typing import Any
from bson import ObjectId
class MongoJSONEncoder(json.JSONEncoder):
def default(self, o: Any) -> Any:
if isinstance(o, ObjectId):
return str(o)
if isinstance(o, datetime):
return str(o)
return json.JSONEncoder.default(self, o)
And then use it to encode the Mongo cursor:
data_json = MongoJSONEncoder().encode(list(cursor))
that you can then load as a Python object with json.loads():
data_obj = json.loads(data_json)

Related

Internationalization in Ktor based website

I'm new to Ktor and Kotlin in general, so please be patient.
I am currently trying to create a little website (mostly for learning) that uses key-value files for internationalization.
I already did something similar in PHP where I just decoded a JSON file and got the value related to the key I passed. This way, I could do something as <p><?php echo $langJson["presentation"][0];?></p> (with $langJson being my json key-value file) so that I would get the proper translation.
I'm trying to do an equivalent in Kotlin using Ktor, but I don't know how to do it. I found the aymanizz ktor-i18n plugin on GitHub that allows to use i18n for internationalization but I don't know if it is really adapted to what I want to do since it detects the language in the header instead of it being chose by the user (with _GET for instance).
Does anyone have any clue on how I could do that?
Briefly, what I want to do is having a single coded page where the content is dynamicly chosen from the accurate language file.
Thank you all! :)
The basic idea is to get a language code from a request (a query parameter, a header, etc), generate a path to an i18n resource file, read it and then deserialize JSON into a map. The resulting map could be used as-is or passed as a model to a template.
Here is an example where I use kotlinx.serialization to transform a JSON string to get a map and FreeMarker template engine to render HTML. To switch a language just use the lang GET parameter, e.g, http://localhost:8080/?lang=es.
import freemarker.cache.ClassTemplateLoader
import io.ktor.application.*
import io.ktor.freemarker.*
import io.ktor.request.*
import io.ktor.response.*
import io.ktor.routing.*
import io.ktor.server.engine.*
import io.ktor.server.netty.*
import kotlinx.serialization.decodeFromString
import kotlinx.serialization.json.Json
fun main() {
embeddedServer(Netty, port = 8080) {
install(FreeMarker) {
templateLoader = ClassTemplateLoader(this::class.java.classLoader, "templates")
}
routing {
get("/") {
call.respond(FreeMarkerContent("index.ftl", mapOf("i18n" to loadI18n(call.request))))
}
}
}.start()
}
fun loadI18n(request: ApplicationRequest): Map<String, String> {
val language = request.queryParameters["lang"] ?: "en"
val filePath = "i18n/$language.json"
val data = object {}.javaClass.classLoader.getResource(filePath)?.readText() ?: error("Cannot load i18n from $filePath")
return Json.decodeFromString(data)
}
resources/templates/index.ftl
<html>
<body>
<h1>${i18n.greetings}</h1>
</body>
</html>
resources/i18n/en.json
{
"greetings": "Hello"
}
resources/i18n/es.json
{
"greetings": "Hola"
}
If you want to fully support of i18n, i recomand to use https://github.com/aymanizz/ktor-i18n. You will have ability to use plulars and other thinks from i18n standart.

error: module xport has no attribute XportReader, python xport file reader

I am importing a module for reading SAS xport files in my main python script. The imported module is called xport.py and has a class XportReader. When I run my original python script it gives an error module xport has no attribute XportReader. I am new to python. Though XportReader is a class why interpreter is considering it as attribute? Any help is much appreciated.
I am executing in Kaggle and My code is like this:
import xport
FN = ['ABC.XPT','xyz.XPT']
def get_data(fname)
with xport.XportReader(fname) as reader:
....
#Read data files
for fn in FN:
fn1=os.path.join("../Data/",fn)
X=get_data(fn1)
....
I have imported data files and xport module is set as utility script.
xport module format-
from datetime import datetime
import struct
..
Methods...
class XportReader(object):
def __init__(..)
....
if __name__ = "__main__":
import sys
with XportReader(sys.argv[1]) as reader:
for obj in reader:
print obj***
Please help. I am using xport.py module for reading NHANES XPT files to obtain raw binary data in pandas dataframe format.

Cannot pass object instance from conftest.py to a test class

I am trying to create a session-scope fixture that creates and pass instance of the driver class for every single test class in my suite. I was expecting that the following code would work:
import pytest
from pages.home.home_page import HomeAdmin
from base.webdriver_factory import WebDriverFactory
#pytest.fixture(scope='session', autouse=True)
def startup(request):
print("SESSION SET UP")
wdf = WebDriverFactory("firefox")
driver = wdf.get_web_driver_instance() # returns driver instance
return driver
I was expecting to have acces to the driver instance from my test code:
from pages.home.home_page import HomeAdmin
import unittest
import pytest
#pytest.mark.usefixtures("startup")
class HomeAdminTest(unittest.TestCase):
#pytest.fixture(autouse=True)
def setup(self, startup):
print("TEST")
self.ha = HomeAdmin(self.driver)
def test_login(self):
print("test run")
Buy this results in an error:
#pytest.fixture(autouse=True)
def setup(self, startup):
print("TEST")
> self.ha = HomeAdmin(self.driver)
E AttributeError: 'HomeAdminTest' object has no attribute 'driver'
testcases\home\home_test.py:11: AttributeError
What I'm trying to achieve in general:
Open browser only once for all tests (all classes and modules) and then run various other classes to manipulate with the same driver instance. (I know that this is not best practice for testing, but this is special case and I am going rather automate some processes than making real tests).
Thank you in advance,
Wojciech
Finally I figured out how to solve problem by myself. It turned out that I was refering to the instance of webdriver in the test class in wrong way. Properly working class looks as following:
from pages.home.home_page import HomeAdmin
import unittest
import pytest
#pytest.mark.usefixtures("startup")
class HomeAdminTest(unittest.TestCase):
#pytest.fixture(autouse=True)
def setup(self,startup):
print("TEST")
self.ha = HomeAdmin(startup)
def test_login(self):
print("test run")
Now I have access to my driver and page class created with it.

importing Network module for clearCookies

I was needing to clearCookies and found a hidden/undocumented function - https://github.com/facebook/react-native/blob/26684cf3adf4094eb6c405d345a75bf8c7c0bf88/Libraries/Network/RCTNetworking.android.js
I am able to access it like this:
import RCTNetworking from 'RCTNetworking'
console.log('RCTNetworking:', RCTNetworking.clearCookies);
It works, but is it correct? Will import RCTNetworking from 'RCTNetworking' work guranteed?
I thought it would be more safe to import from NativeModules like this:
import { NativeModules } from 'react-native'
console.log('Networking:', NativeModules.Networking.clearCookies);
However this imports the whole NativeModules which has a bunch of other stuff. Wouldn't this be bad? Or does tree shakingng in production remove all the stuff I don't use from NativeModules?
Is there another way to access clearCookies? Is this documented anywhere?
I imported RCTNetworking like this: var RCTNetworking = require("RCTNetworking"); This import is guaranteed to work on all platforms.
I couldn't find any documentation for RCTNetworking nor for the clearCookies() function

Convert Type "String" to type "Name"

Here is the Problem:
import lotus.domino.Document;
import lotus.domino.Name;
import lotus.domino.NotesException;
import lotus.domino.Session;
import de.bcode.utils.Utils;
public class Example {
int x;
Name n = (Name)x.toString(); // i want to do this.
}
I am trying to convert above and i also did it by "typecasting" and it has been failing.
Thank you for reading all the question :-)
The API documentation of IBM Notes explains that a Name object can only be obtained from the Session. "To create a new Name object, use createName in Session. " see this page
Session s = NotesFactory.createSession();
Name n = s.getUserNameObject();
I guess this will help.Try this
import lotus.domino.Document;
import lotus.domino.Name;
import lotus.domino.Session;
public class Example {
int x;
Name n= createName(x.toString());
}