I currently have a class urldata.py, with a loop:
from Scanner.views import Processinitialscan
for element in elements:
dbInsert = PathsOfDomain(pathToScan=element.attrs["href"],FKtoTld=Processinitialscan.)
dbInsert.save()
I have a view.py with a variable EnteredDomainRowID, that I want to use in the class above:
def Processinitialscan(request):
EnteredDomainRowID = GetEnteredDomainObjects.pk
I've been trying:
FKtoTld=Processinitialscan.EnteredDomainRowID
in :
dbInsert = PathsOfDomain(pathToScan=element.attrs["href"],FKtoTld=Processinitialscan.)
but, this doesn't seem to work.
My question, how do I access the value from the variable EnteredDomainRowID from views.py within my class urldata.py for the variable dbInsert (as shown above) ?
Additionally, I cannot seem to be able to import views.py into a urldata.py , is this not possible?
Any help is really, really appreciated.
Thank you.
Unfortunately, that's not the way python works EnteredDomainRowID is not a property of your function object, but it is a local variable to the function.
You could pretty easily convert this to a class based view, which will allow you to easily access the classes attributes.
Related
Within a class in Python:
I have this variable that I pass through a function called "changers"
energy_L_gainer = changers('cap_largeover,','sec_energy','-change')
When I call upon this variable from another function, how can I get it to pass back through the function again to refresh the data in the variable. I have searched everywhere and tried all that my small mind could muster, and I cannot get it to work. Any ideas? Thank you all so much.
Can you rerun the class somehow within the function to refresh the variables?
I called upon this variable within another function using:
self.energy_L_gainer
Here is the changers function for reference:
def changers(cap, sec, sort):
screen = requests.get(f'https://finviz.com/screener.ashx?v=111&f={cap}{sec},geo_usa&ft=4&o={sort}', headers = headers).text
tables = pd.read_html(screen)
tables = tables[-2]
tables.columns = tables.iloc[0]
tables = tables[1:]
return tables
Make it a property on your class
#property
def energy_L_gainer(self):
return changers('cap_largeover,','sec_energy','-change')
Now any reference to self.energy_L_gainer will use the result of that function
I'm not quite sure I'm following you, but you probably need to use self.energy_L_gainer = instead of energy_L_gainer =. In Python those two aren't the same like they can be in some other languages.
Learning class in python, using below github(https://github.com/gurupratap-matharu/Bike-Rental-System), I cloned it and I try to add database class. I did it and it works. But I don't think I did it correctly (pythonically or object oriented correctly). Can someone please do a code review? ( https://github.com/isolveditalready/PLAYGROUND ) I am espescailly not sure if using another class's variable in another class( in dbAction.py, line 15)
Basically, I needed to access another class's variable(From class BikeRental class, variable named stock) from dbActionMe class and I didn't know how so I just passed that variable into dbActionMe class.
If code review is not possible, can someone please review below to see what I could have done differently?
db = dbActionMe()
numOfBikes = db.dbRead()
shop = BikeRental(numOfBikes)
customer = Customer()
...
db.dbUpdate(shop.stock)
Firstly, I do apologise as I'm not quite sure how to word this query within the Python syntax. I've just started learning it today having come from a predominantly PowerShell-based background.
I'm presently trying to obtain a list of projects within our organisation within Google Cloud. I want to display this information in two columns: project name and project number - essentially an object. I then want to be able to query the object to say: where project name is "X", give me the project number.
However, I'm rather having difficulty in creating said object. My code is as follows:
import os
from pprint import pprint
from googleapiclient import discovery
from oauth2client.client import GoogleCredentials
credentials = GoogleCredentials.get_application_default()
service = discovery.build('cloudresourcemanager', 'v1', credentials=credentials)
request = service.projects().list()
response = request.execute()
projects = response.get('projects')
The 'projects' variable then seems to be a list, rather than an object I can explore and run queries against. I've tried running things like:
pprint(projects.name)
projects.get('name')
Both of which return the error:
"AttributeError: 'list' object has no attribute 'name'"
I looked into creating a Class within a For loop as well, which nearly gave me what I wanted, but only displayed one project name and project number at a time, rather than the entire collection I can query against:
projects=[]
for project in response.get('projects', []):
class ProjectClass:
name = project['name']
projectNumber = project['projectNumber']
projects.append(ProjectClass.name)
projects.append(ProjectClass.projectNumber)
I thought if I stored each class in a list it might work, but alas, no such joy! Perhaps I need to have the For loop within the class variables?
Any help with this would be greatly appreciated!
As #Code-Apprentice mentioned in a comment, I think you are missing a critical understanding of object-oriented programming, namely the difference between a class and an object. Think of a class as a "blueprint" for creating objects. I.E. your class ProjectClass tells python that objects of type ProjectClass will have two fields, name and projectNumber. However, ProjectClass itself is just the blueprint, not an object. You then need to create an instance of ProjectClass, which you would do like so:
project_class_1 = ProjectClass()
Great, now you have an object of type ProjectClass, and it will have fields name and projectNumber, which you can reference like so:
project_class_1.name
project_class_1.projectNumber
However, you will notice that all instances of the class that you create will have the same value for name and projectNumber, this just won't do! We need to be able to specify values when we create each instance. Enter init(), a special python method colloquially referred to as the constructor. This function is called by python automatically when we create a new instance of our class as above, and is responsible for setting up all the fields of that class. Another powerful feature of classes and objects is that you can define a collection of different functions that can be called at will.
class ProjectClass:
def __init__(self, name, projectNumber):
self.name = name
self.projectNumber = projectNumber
Much better. But wait, what's that self variable? Well, just as before we were able reference the fields of our instance via the "project_class_1" variable name, we need a way to access the fields of our instance when we're running functions that are a part of that instance, right? Enter self. Self is another python builtin parameter that contains a reference to the current instance of the ProjectClass that is being accessed. That way, we can set fields on the instance of the class that will persist, but not be shared or overwritten by other instances of the ProjectClass. It's important to remember that the first argument passed to any function defined on a class will always be self (except for some edge-cases you don't need to worry about now).
So restructuring your code, you would have something like this:
class ProjectClass:
def __init__(self, name, projectNumber):
self.name = name
self.projectNumber = projectNumber
projects = []
for project in response.get('projects', []):
projects.append(ProjectClass(project["name"], project["projectNumber"])
Hopefully I've explained this well and given you a complete answer on how all these pieces fit together. The hope is for you to be able to write that code on your own and not just give you the answer!
I've looked at documentation, and have searched Google extensively, and haven't found a solution to my problem.
This is my readRSS function (note that 'get' is a method of Kenneth Reitz's requests module):
def readRSS(name, loc):
linkList = []
linkTitles = list(ElementTree.fromstring(get(loc).content).iter('title'))
linkLocs = list(ElementTree.fromstring(get(loc).content).iter('link'))
for title, loc in zip(linkTitles, linkLocs):
linkList.append((title.text, loc.text))
return {name: linkList}
This is one of my MongoAlchemy classes:
class Feed(db.Document):
feedname = db.StringField(max_length=80)
location = db.StringField(max_length=240)
lastupdated = datetime.utcnow()
def __dict__(self):
return readRSS(self.feedname, self.location)
As you can see, I had to call the readRSS function within a function of the class, so I could pass self, because it's dependent on the fields feedname and location.
I want to know if there's a different way of doing this, so I can save the readRSS return value to a field in the Feed document. I've tried assigning the readRSS function's return value to a variable within the function __dict__ -- that didn't work either.
I have the functionality working in my app, but I want to save the results to the Document to lessen the load on the server (the one I am getting my RSS feed from).
Is there a way of doing what I intend to do or am I going about this all wrong?
I found out the answer. I needed to make use of a computed_field decorator, where the first argument was the structure of my return value and deps was a set which contained the fields that this field was dependent on. I then passed the dependent fields into a function's arguments and there you have it.
#fields.computed_field(db.KVField(db.StringField(), db.ListField(db.TupleField(db.StringField()))), deps=[feedname, location])
def getFeedContent(a=[feedname, location]):
return readRSS(a['feedname'], a['location'])
Thanks anyway, everyone.
Is there a way to get the key (or id) value of a db.ReferenceProperty, without dereferencing the actual entity it points to? I have been digging around - it looks like the key is stored as the property name preceeded with an _, but I have been unable to get any code working. Examples would be much appreciated. Thanks.
EDIT: Here is what I have unsuccessfully tried:
class Comment(db.Model):
series = db.ReferenceProperty(reference_class=Series);
def series_id(self):
return self._series
And in my template:
more
The result:
more
Actually, the way that you are advocating accessing the key for a ReferenceProperty might well not exist in the future. Attributes that begin with '_' in python are generally accepted to be "protected" in that things that are closely bound and intimate with its implementation can use them, but things that are updated with the implementation must change when it changes.
However, there is a way through the public interface that you can access the key for your reference-property so that it will be safe in the future. I'll revise the above example:
class Comment(db.Model):
series = db.ReferenceProperty(reference_class=Series);
def series_id(self):
return Comment.series.get_value_for_datastore(self)
When you access properties via the class it is associated, you get the property object itself, which has a public method that can get the underlying values.
You're correct - the key is stored as the property name prefixed with '_'. You should just be able to access it directly on the model object. Can you demonstrate what you're trying? I've used this technique in the past with no problems.
Edit: Have you tried calling series_id() directly, or referencing _series in your template directly? I'm not sure whether Django automatically calls methods with no arguments if you specify them in this context. You could also try putting the #property decorator on the method.