Get by name in google app engine - python

Instead of using get_by_id() method for getting the id of a specific entry and print the content of this entry from the google datastore, i am trying to get the name of the url and print the content. For example:
print all the content that have this specific name(may have more than one rows of content with this name)
print the content of the specific id
i am using get_by_id(long(id)) to get the id in the second part of my example, and its working. I am trying to use get_by_key_name(name) but it does not working. any ideas on that? thank you.
sorry, but since i couldn't leave a comment, i am editing my question. Basically, since now i can get all the name of animals from my datastore and i have made them clickable using an html code in template file. In the datastore, there are entries with the same name of animal more than one times (e.g. name= duck, content= water and name=duck, content=lake). Now, when i am clicking into every name of animals(i have use the DINSTINCT in my gql query to print redundant elements(e.g. duck) only one time).Since the name=duck has two contents, when i am clicking on the name of the duck i want to see both of the contents. My problem is if i am using get_by_id(long(id)) i get the unique id of every element. But this will not print me both of the content of the name=duck because every entry has a unique id. But i want all the content of the entries with the same name. I am trying the following but it does not working.
msg = MODEL.Animals.get_by_key_name(name)
self.response.write("%s" % msg.content)

With get_by_id() you can get entity only if you know this ID. This operations named "Small operations" in quota and they are cheaper than datastore reads, but to get list of entities filtered by indexed property - you should use filters.
query = MODEL.Animals.query()
query = query.filter(MODEL.Animals.name == 'duck')
ducks = query.fetch(limit=100) # limit number of returned animals
for duck in ducks:
self.response.write('%s - %s' % (duck.name, duck.content))
By default, all string properties are indexed, so you will be able to do such requests.

Related

Is there a way to search user/screen names in tweepy (or any other API package) using partial names like using contains or %?

So I am able to lookup users using the below command...
Search = 'Amazon'
users = api.search_users(q = Search)
results = []
for user in users:
name = user.name
screen_name= user.screen_name
results.append([name, screen_name])
results = pd.DataFrame(results)
results.columns = ['name', 'screen_name']
results
...and I was wonder if there was a way to use some form of contains/islike/% lookup when I only know part of the name. So for instance. If I was looking for Amazon, could I do something where I state theat
api.search_users(q is like 'Amaz%')
Furthermore, I believe that the search_users function is looking up by the screen name. Is there a function that looks it up by the user name instead?
There is no Twitter API function for this (wildcard or contains lookup, or user name instead of screen name), so there is no way for Tweepy or other libraries to offer the functionality.
We are as persian and other languages users cant use it cuz we just cant show our exact name inside an english alphabet user_id and we allways use and search people with their unicode display names.

How use Flask LinkCol on database query data results?

I have been working with Flask for a little while and developed a database manager application for managing internal data for the department I work in (I am not a "real" developer but have learned by doing/necessity). The application works great as a basic CRUD app. In it I have used Flask forms and tables including the LinkCol column for linking to different functions within the app. In those cases, I am using an 'Edit' or 'Delete' clickable link; meaning every column in the table has an extra cell with that word. Clicking either of those takes the user to the corresponding page where they can take appropriate action on that item.
Currently I am trying to use LinkCol so that data returned from the database can be the clickable link that links to another function rather than every table having an additional column (for example, "Go to Account"). So, when my table populates with an account number, the user can click the actual account number in the table to go to a different page to view additional data about that specific account. I read the docs and looked at the examples on the creators page regarding overwriting things in the classes but haven't been able to figure it out. I have written a few of my own classes, but am not an expert on the matter by any means. I also have been unable to find anything else that might help including on SO which is always my go to resource for figuring things out.
Here is my table definition using a LinkCol that renders incorrectly and puts 'Account #' in each cell instead of the dynamic data I would like. Changing to Col gives correct display but I want it to be clickable:
class AccountsResults(MainTable):
AccNo = LinkCol('Account #','dbhome_bp.route.account_detail', url_kwargs=
dict(AccNo='AccNo',StatusCode='Active',ServiceAddress1=\
'ServiceAddress1'))
TnCount = Col('Total TNs')
ServiceAddress1 = Col('Service Address')
ServiceCity = Col('Service City')
ServiceZip = Col('Service Zip Code')
MasterServiceDate = Col('Master Service Date')
Active = Col('Currently Active')
Here is an example of what I know I can do versus what I would like to do.
Can do ('Go To Account' is clickable in the Go To Account column):
Go To Account
Account #
Service Address
Etc.
Go To Account
12345678
1234 Anywhere
Yup
Go To Account
12345679
5678 Somewhere
Nah
Would like to do (Account numbers are clickable in Account # column ):
Account #
Service Address
Etc.
12345678
1234 Anywhere
Yup
12345679
5678 Somewhere
Nah
Does anyone know how to make the dynamic data returned from a query the clickable link for a LinkCol in Flask Table?
Any help is greatly appreciated.
Assuming an Sqlalchemy model Account with PK column id and a route defined as follows:
accounts = Blueprint('accounts', __name__)
#accounts.route("/accounts/<int:account_id>")
def detail(self, account_id):
_account = Account.get_or_404(account_id)
# show account details
return render('account-details.html', account=_account)
Define your account link column as follows:
account = LinkCol(
name='Account #',
attr='id',
endpoint='accounts.detail',
url_kwargs=dict(account_id='id'),
)
The parameter meanings are as follows:
name # the column header text
attr # the name of the attribute of the account object to render as the text in the <td> cell
endpoint # the endpoint to link to
url_kwargs # the arguments that get passed to the url_for function along with the endpoint
The links would be constructed as if you had done a url_for for each row in the table as follows:
_row_account_detail_url = url_for('accounts.detail', account_id=row_id)
Example Table definition:
class AccountTable(Table):
account = LinkCol(
name='Account #',
attr='id',
endpoint='accounts.detail',
url_kwargs=dict(account_id='id'),
)
service_address = Col(
'Service Address',
attr='service_address'
)
# other columns

python database table linking

I'm new to Python and I'm trying to make a simple bulletin board system app using web2py. I am trying to add a post into a certain board and I linked the post and board by including the following field in my post table: Field('board_id', db.board). When I try to create a post inside a particular board it gives me an error: "OperationalError: no such column: board.id". My code for create_posts:
def add_post():
board = db.board(request.args(0))
form = SQLFORM(db.post)
db.pst.board_id.default = db.board.id
if form.process().accepted:
session.flash = T('The data was inserted')
redirect(URL('default', 'index'))
return dict(form=form, board=board)
When I try to do {{=board}} on the page that shows the posts in a certain board, I get Row {'name': 'hi', 'id': 1L, 'pst': Set (pst.board_id = 1), 'description': 'hi'} so I know it's there in the database. But when I do the same thing for the "add post" form page, it says "board: None". I'm extremely confused, please point me in the right direction!
There appear to be several problems with your function. First, you are assigning the default value of the board_id field to be a Field object (i.e., db.board.id) rather than an actual id value (e.g., board.id). Second, any default values should be assigned before creating the SQLFORM.
Finally, you pass db.post to SQLFORM, but in the next line, the post table appears to be called db.pst -- presumably these are not two separate tables and one is just a typo.
Regarding the issue of {{=board}} displaying None, that indicates that board = db.board(request.args(0)) is not retrieving a record, which would be due to request.args(0) itself being None or being a value that does not match any record id in db.board. You should check how you are generating the links that lead to add_post and confirm that there is a valid db.board id in the first URL arg. In any case, it might be a good idea to detect when there is no valid board record and either redirect or display an error message.
So, your function should look something like this:
def add_post():
board = db.board(request.args(0)) or redirect(URL('default', 'index'))
db.pst.board_id.default = board.id
form = SQLFORM(db.pst)
if form.process(next=URL('default', 'index'),
message_onsuccess=T('The data was inserted'))
return dict(form=form, board=board)
Note, if your are confident that links to add_post will include valid board IDs, then you can eliminate the first line altogether, as there is no reason to retrieve a record based on its ID if the only field you need from it is the ID (which you already have). Instead, the second line could be:
db.pst.board_id.default = request.args(0) or redirect(URL('default', 'index'))

Google app engine IN filter

I am using python 2.7, jinja2 and google app engine.
I have a database where one of the entities are string in this form:
"test1,test2,test3,test4,test5"
I try to figure a query where I will retrieve all the entities where test1 for example are in the string.
I tried the following where tags is the string property:
category = "test1"
mymodel.gql("WHERE tags in :1", category)
I have this error : BadArgumentError: List expected for "IN" filter
I can imagine that this is logical, since my property is string and not list, but how can I change the query to make it work?
You would have to modify you property to be a StringListProperty rather than string for this to work.
There are not a lot of other choices either. Use FullText Search is or something like WHoosh https://github.com/tallstreet/Whoosh-AppEngine which also does full text search are your other alternatives.
I would personally change it to a StringListProperty.
As the error indicates, the GQL is expecting a list. Try making category a list:
category = ["test1"]

Python search for value in string using wildcards

I'm trying to make an address book for a school project, but I can't get my head around searching for values when part of the value is queried.
Here is the block of code at which I am stuck on:
self.ui.tableWidget.setRowCount(0)
with open("data.csv") as file:
for rowdata in csv.reader(file):
row = self.ui.tableWidget.rowCount()
if query in rowdata:
self.ui.tableWidget.insertRow(row)
for column, data in enumerate(rowdata):
item = QtGui.QTableWidgetItem(data)
self.ui.tableWidget.setItem(row, column, item)
As you can see, I'm using a PyQt TableWidget to display search results from a csv file. The code above does work, but it only displays the result when a full query is given. The line of code that checks for a match is:
if query in rowdata:
So for example, if I wanted to find someone called John, I would have to search for exactly "John". It wouldn't appear if I searched "Joh" or "john" or "hn" and so on...
If you require more information, just ask :P
What I think you want to do is search for query within the fields of your rows, not the whole row at once.
The problem you're having is that string in obj does different things depending on what type obj has. If it is a string, it does a substring search (like you want). If it is a non-string container however, it does a regular membership check (which is why it only finds exact matches now).
So to fix it, change your test from if query in rowdata to if any(query in field for field in rowdata). If you only want to search for matches within a specific field (like the contact's name) then it could be even simpler: if query in rowdata[name_column] (where name_column is the number of the column of the name field is in your CSV file).

Categories

Resources