Found 27104 Articles for Server Side Programming

How to encode custom python objects as BSON with Pymongo?

Rajendra Dharmkar
Updated on 16-Jun-2020 11:29:35

278 Views

To encode custom python objects as BSON with Pymongo, you have to write a SONManipulator. From the docs:SONManipulator instances allow you to specify transformations to be applied automatically by PyMongo.from pymongo.son_manipulator import SONManipulator class Transform(SONManipulator):   def transform_incoming(self, son, collection):     for (key, value) in son.items():       if isinstance(value, Custom):         son[key] = encode_custom(value)       elif isinstance(value, dict): # Make sure we recurse into sub-docs         son[key] = self.transform_incoming(value, collection)     return son   def transform_outgoing(self, son, collection):     for (key, value) in son.items():       ... Read More

How to know if an object has an attribute in Python?

Gireesha Devara
Updated on 29-Aug-2023 03:41:46

21K+ Views

Python is an object-oriented programming language, here attributes are known as properties of an object. By using different methods, we can check if an object has an attribute or not. To check if an object contains a particular attribute then we can use hasattr() method and getattr() method. Or if we want to get all existing attributes then we can use the dir() method. (Learn more about Python directories: Python Directories Tutorial) Initially create a dummy Python class with two attributes then assign it to an object, and it will refer throughout this article. class DummyClass(): ... Read More

How to insert a Python object in MySQL?

Rajendra Dharmkar
Updated on 28-Jan-2020 06:11:54

740 Views

Assuming that a MySQL database named 'test' is present on the server and a table named employee is also created. Let the table have five fields fname, lname, age, gender, and salary.Suppose we want to insert a tuple object containing data of a record defined as follows into the Msql database.t1=('Steven', 'Assange', 21, 'M', 2001)To establish an interface between MySQL and Python 3, you need to install the PyMySQL module. Then you can set up the connection using the following statementsimport PyMySQL # Open database connection db = PyMySQL.connect("localhost", "root", "", "test" ) # prepare a cursor object using cursor() ... Read More

How to insert a Python object in Mongodb?

Rajendra Dharmkar
Updated on 16-Jun-2020 07:36:08

570 Views

You can use the pymongo library in Python to connect to a MongoDB database and use it to insert, update, delete, etc objects in Python. The library supports Python datetime objects out of the box and you dont need to do anything special to insert dates in Mongo using PyMongo. For example, Examplefrom pymongo import MongoClient # This will try to connect to MongoDB on the default port and host client = MongoClient() db = client.test_database # Insert the given dictionary to the objects collection: result = db.objects.insert_one({"last_modified": datetime.datetime.utcnow()}) print("Object inserted!")OutputThis will give the output −Object inserted!Note − Always use ... Read More

How to compress Python objects before saving to cache?

Rajendra Dharmkar
Updated on 30-Jul-2019 22:30:21

242 Views

We need sometimes to compress Python objects (list, dictionary, string, etc) before saving them to cache and decompress after reading from cache.Firstly we need to be sure we need to compress the objects. We should check if  the data structures/objects are too big just to fit uncompressed in the cache. There is going to be an overhead for compression/decompression, that we have to tradeoff with the gains made by caching in the first place.If we really need compression, then we probably want to use zlib.If we are going to use zlib, we might want to experiment with the different compression ... Read More

How to use Python object in C++?

Rajendra Dharmkar
Updated on 10-Feb-2020 10:49:28

681 Views

Here is an example in which a simple Python object is wrapped and embedded. We are using  .c for this, c++ has similar steps −class PyClass(object):     def __init__(self):         self.data = []     def add(self, val):         self.data.append(val)     def __str__(self):         return "Data: " + str(self.data) cdef public object createPyClass():     return PyClass() cdef public void addData(object p, int val):     p.add(val) cdef public char* printCls(object p):     return bytes(str(p), encoding = 'utf-8')We compile with cython pycls.pyx (use --cplus for c++) to generate ... Read More

How to get the return value from a function in a class in Python?

Rajendra Dharmkar
Updated on 09-Sep-2023 23:05:46

12K+ Views

The following code shows how to get return value from a function in a Python class.Exampleclass Score():     def __init__(self):         self.score = 0         self.num_enemies = 5         self.num_lives = 3     def setScore(self, num):         self.score = num     def getScore(self):          return self.score     def getEnemies(self):         return self.num_enemies     def getLives(self):         return self.num_lives         s = Score() s.setScore(9) print s.getScore() print s.getEnemies() print s.getLives()Output9 5 3

How to return an object from a function in Python?

Rajendra Dharmkar
Updated on 09-Sep-2023 23:08:13

13K+ Views

The return statement makes a Python function to exit and hand back a value to its caller. The objective of functions in general is to take in inputs and return something. A return statement, once executed, immediately halts execution of a function, even if it is not the last statement in the function.Functions that return values are sometimes called fruitful functions.Exampledef sum(a, b):      return a+b sum(5, 16)Output21Everything in Python, almost everything is an object. Lists, dictionaries, tuples are also Python objects. The code below shows a Python function that returns a Python object; a dictionary.Example# This function returns ... Read More

How do you compare Python objects with .NET objects?

Rajendra Dharmkar
Updated on 30-Jul-2019 22:30:21

124 Views

By default, all .NET objects are reference types and their equality and hash code is determined by their memory address. Additionally, assigning a variable to an existing object just makes it point to that address in memory, so there is no costly copying occurring. It appears that this is true for python objects as well to certain extent.Properties of Python objects: All python objects havea unique identity (an integer, returned by id(x)); a type (returned by type(x))You cannot change the identity; You cannot change the type.Some objects allow you to change their content (without changing the identity or the type, that is).Some ... Read More

How to convert JSON data into a Python object?

Niharika Aitam
Updated on 15-May-2023 13:55:27

758 Views

JSON can be abbreviated as JavaScript Object Notation. Json means a script of a text file in a programming language to transfer and store the data. Json supported by the python programming language using a built-in package named json. The Json text is given in the quoted string format which contains in the key and value within the curly braces{}. This looks like a dictionary format in python programming language. For using this json package in the python programming language we have to import the json package in python script. In the Json package we have so ... Read More

Advertisements