Python SESSION (like php) class - python

is there any class to handle a SESSION (like php) in Python? not in django, but I want to use it with PyQt
thank you

The short answer is that there is no $SESSION variable in Python.
Python tends not to put things in global scope like PHP. Therefore, if you are accessing a user's session id, it will probably be accessed via dot notation module_name.ClassName.session. If you would like to create a PyQt app that acts as a webserver, you could probably adapt a web framework's implementation.
Others' responses to similar queries suggest implementing sessions via a simple database[1]. You could try assigning unique ids with uuid, and storing them with tools like sqlite3 or pickle.
[1] http://ubuntuforums.org/showthread.php?t=859645

Theres a session class with mod_python for apache, that can be a good starting point for making our own class. The class is not very dependent on apache to work.
http://www.modpython.org/

Related

Using Python Objects in Django Applications

I apologize if this seems like a stupid question but I'm still very much a novice Python/Django programmer. Is it normal to create Python objects in a Django application that aren't models that will be saved in the database?
I'm creating what's become a fairly large Django application and, to me, my code is really starting to "smell". What I mean is that my views are becoming very large because I'm taking a procedural rather than object-oriented approach. My intuition tells me that my code might be simpler, easier to test, and more robust in the long run if I were using more objects with their own attributes and behaviors rather than passing information from one function to the next in my views.
What's hanging me up is that these aren't objects I want to save in my database so I don't quite know if I should be using them and, if I should, where I'd put them. Is the approach I'm proposing typical in a Django application? If so, where would I store those objects with respect to the Django model/view/template structure? Also, are there any popular Django modules or libraries that do what I'm describing that I should study?
Thanks in advance for your response.
You can store your objects anywhere. There could be helper functions in your views file or models file or wherever. I prefer to put miscellaneous functions in a utils.py file but that is not a convention, just something I end up doing. I end up putting most of miscellaneous helper functions and base classes in a common app, and more specifically a common.utils file.
In one project I have lots of apps, and each app has an api client. The base class for the client resides in an app called common. Then each app then has their specific client in client.py file
project
common
client
app1
client
app2
client
Then in app1 client
from project.common.client import BaseClient
class ConcreteApp1Client(BaseClient):
pass
Then in my views or management commands or models or wherever the concrete client can be imported and used as normal. from project.app1.client import ConcreteApp1Client
Django also has class-based views if you feel certain variables could best be encapsulated in a class.
https://docs.djangoproject.com/en/dev/topics/class-based-views/

Accessing Pyramid DB Session within third-party library

I am writing a library for Pyramid. One aspect involves the library being provided with a model class, then retrieving all instances of the model from the database. However, I am unable to interact with the DB without access to the session factory.
In Django this was taken care of behind the scenes. With Pyramid & SQLAlchemy this is not the case.
Is there a standard way for me to get hold of the current thread's DB Session within Pyramid, and without having any knowledge of how a particular project is setup (as this is a reusable library)?
PS. I'm still getting my head around this area of SQLAlchemy, so please excuse any confusion.
You could specify sqla session as attribute in inherited classes, like factory-boy does:
https://factoryboy.readthedocs.org/en/latest/orms.html?highlight=sqlalchemy#sqlalchemy
Another way is create interface and require to register sqlalchemy session in application registry as utility, before "config.include" your extension. Maybe pyramid_jinja2 will clarify this solution.
I recommend reading about
a convention to add session to the request object. Your library makes just an assumption about that and write that in your package docs.
http://blog.safaribooksonline.com/2014/01/07/building-pyramid-applications/
Global vs. Non-Global session
http://docs.pylonsproject.org/projects/pyramid_cookbook/en/latest/database/sqlalchemy.html
A offical tutorial showing those concepts
http://docs.pylonsproject.org/projects/pyramid/en/master/quick_tutorial/databases.html
A lot of pyramid applications use the package zope.sqlalchemy to integrate application transaction management and DB session management. This approach is even recommended as one of many options by SQLAlchemy docs. Docs of zope.sqlalchemy are a bit confusing at least to me. The topic as a whole is a constant source of confusion to people starting with pyramid and thread-local sessions using SQLAlchemy.
To see a full-featured pyramid app that makes use of these packages look at ToDoPyramid - one of the sample application listed on pyramid docs pages
I cloned the project to make the database-related code at least more testable and readable to me. I found the concepts work very well - if the environment targetting the database is setup up properly.

Using the same database abstraction in Flask and non-Flask program

Basically, I am trying to share as much database layer code as possible between a Flask application (for a REST API) and a non-Flask API.
Is it a good idea to use the same Flask-SQLAlchemy layer in both the pure Python API (intended to be imported in non-web Python applications) and in the REST API Flask daemon?
I guess another way to phrase, though I am not sure on the terminology, "how do I best share database model between Flask app and a separate Python import library?"
Or from another angle, is there any point in using Flask-SQLAlchemy in a Flask REST API, if you also want to share the SQL abstraction with an import library. Is it better then to use plain SQLAlchemy?
Use case: we have a large database with many tables, and want to build both a REST API (for customer access) and a Python import library (for performant internal tools) for accessing the database, but of course share as much code between them as possible.
Related:
Using Flask-SQLAlchemy in Blueprint models without reference to the app
What's your folder layout for a Flask app divided in modules?
SQLAlchemy with Flask -- hybrid models?
Using Flask-SQLAlchemy models out of a web context is a matter of creating a Flask application and call
app.test_request_context().push()
The point here is what you will do with your "non web" library.
If it's not a problem to have the whole Flask library installed when you need to use the library then there's no problem at all using it in that way.
If you plan to make performance improvements in the library data accessing code, like using different sessions, concurrency and such, then you're modifying your initial code so it's a totally different scenario. In this case a pure-SQLAlchemy approach might be better but it really depends on the differences between the two patterns.
Normally with models comes methods and using 2 different ORM patterns (Flask-SQLAlchemy wrapper models and pure SQLAlchemy) means duplicating code.

Sharing objects between applications

I am trying to share an object between two GAE apps. The first will have the class's file, and will offer up an instance of that object. The second, using a given url, will access the first app, get the object and then use is. Is this actually possible? If so what am I not doing right in the code below?
As a small side note I tried a solution with pickle, but both apps are required to have the class in its name space, but I will be working with a number of these. I thought about trying to imitate something like Java's abstract class by using inheritance, but that didn't work out. I can provide that code too if you want to see it.
I understand the possible Terms of Service, that is not a issue.
I know cloud computing is out there, I don't know how to work with it, and I would
prefer to avoid the costs because I am developing this as a class project.
I have seen some suggestions to use remote_api, but I have seen no good example
of how it can be used, let alone used to allow two applications to interact.
I have seen the solution to use multiple versions, but each student will have
an app, it would be incredibly messy, but possibly doable.
First.Py:
class SampleCritter():
def move():
...
class Access(webapp2.RequestHandler):
def post(self):
CritStore(stats=self.request.body).put()
def get(self):
creature = CritStore.all().order('-date').get()
if creature:
stats = loads(creature.stats)
return SampleCritter(stats)
else:
return SampleCritter()
Second.py:
class Out(webapp2.RequestHandler):
def post(self):
url = self.request.POST['url']
critter = urllib2.urlopen(url)
critter.move()
The short answer is, you can't share objects between apps.
The longer answer is, your first app can expose objects using an HTTP based API. Any client can access the HTTP API, including app 2.
App 2 will have to manipulate objects via the HTTP API. You won't be able to call critter.move() from app 2, though if you create a handler say, critter\move, you can have the handler pull up the appropriate Critter instance and call move() on it. You'll have to pass all the appropriate params via HTTP POST as well.

cherrypy dynamically add objects

I'm using cherrypy to mimic an existing RESTful interface. One requirement is that I have is to be able to add objects on the fly.
So, for example, let's say I have an object, called myobj. I want to be able to expose a method that is based on an object added by the user. So, I would have an "add" context, where I create the object
http://example.ex/myobj+create
and I would be able to retrieve the object that's created, as well as any children:
http://example.ex/myobjs/obj1
http://example.ex/myobjs/obj1/child1
Is this possible with cherrypy? Should I be investigating a different framework?
You probably want to look at the _cp_dispatch or popargs facilities that CherryPy 3.2+ offers. They are less known and unfortunately I couldn't find proper doc for them but they would do what you're after. Alternatively, you could use the Routes or selector dispatchers.
Yes, you can add handlers dynamically. Just execute obj1.child1 = Child(...).
CherryPy 3.2 (REST) provides an interface for creating RESTful interfaces.

Categories