python-2.7,google-app-engine,gae-datastore,jinja2 , I am working on small project with Google AppEngine (Python), tutored by Udacity. I am unable to render user comments to main page


I am working on small project with Google AppEngine (Python), tutored by Udacity. I am unable to render user comments to main page

Question:

Tag: python-2.7,google-app-engine,gae-datastore,jinja2

I am suppose to add forms to my HTML to allow users to add data (comments to my page) and also store the data via GAE-Datastore. I have been able to store the data but not able to get the user comments posted to the main page.

Seperate code files:

index.yaml

indexes:
- kind: Section
  ancestor: yes
  properties:
- name: date
  direction: desc

app.yaml

application: addnotes
version: 1
runtime: python27
api_version: 1
threadsafe: true

# [START handlers]
handlers:
- url: /stylesheets
  static_dir: stylesheets

- url: /.*
  script: addnotes.app  
# [END handlers]

# [START libraries]
libraries:
- name: webapp2
  version: latest
- name: jinja2
  version: latest  
# [END libraries]

addnotes.py

import os
import urllib`

from google.appengine.api import users
from google.appengine.ext import ndb

import jinja2
import webapp2

JINJA_ENVIRONMENT = jinja2.Environment(
    loader=jinja2.FileSystemLoader(os.path.dirname(__file__)),
    extensions=['jinja2.ext.autoescape'],
    autoescape=True)`

DEFAULT_SECTION_NAME = 'General_Submission'

# We set a parent key on the 'Comment' to ensure that they are all  
# in the same entity group. Queries across the single entity group  
# will be consistent.  However, the write rate should be limited to
# ~1/second.  

def section_key(section_name=DEFAULT_SECTION_NAME):
    """Constructs a Datastore key for a Section entity.

    We use section_name as the key.
    """
    return ndb.Key('Section', section_name)`

# [START comment]
# These are the objects that will represent our Author and our Post. We're using
# Object Oriented Programming to create objects in order to put them in Google's
# Database. These objects inherit Googles ndb.Model class.

class Author(ndb.Model):
  """Sub model for representing an author."""
  identity = ndb.StringProperty(indexed=True)
  email = ndb.StringProperty(indexed=False)

class Comment(ndb.Model):
"""A main model for representing an individual Guestbook entry."""
author = ndb.StructuredProperty(Author)
content = ndb.StringProperty(indexed=False)
date = ndb.DateTimeProperty(auto_now_add=True)

# [END comment]

class Handler(webapp2.RequestHandler): 
    """
    Basic Handler; will be inherited by more specific path Handlers
    """
    def write(self, *a, **kw):
        "Write small strings to the website"
        self.response.out.write(*a, **kw)  

    def render_str(self, template, **params):  
        "Render jija2 templates"
        t = JINJA_ENVIRONMENT.get_template(template)
        return t.render(params)   

    def render(self, template, **kw):
        "Write the jinja template to the website"
        self.write(self.render_str(template, **kw))

# [START main_page]
class MainPage(webapp2.RequestHandler):
    def get(self):
        section_name = self.request.get('section_name', DEFAULT_SECTION_NAME)
        if section_name == DEFAULT_SECTION_NAME.lower(): section_name = DEFAULT_SECTION_NAME

        comments_query = Comment.query(ancestor=section_key(section_name)).order(-Comment.date)

        comment = comments_query.fetch(10)

        # If a person is logged in to Google's Services
        user = users.get_current_user()
        if user:
            url = users.create_logout_url(self.request.uri)
            url_linktext = 'Logout'
        else:
            user = 'Anonymous Poster'
            url = users.create_login_url(self.request.uri)
            url_linktext = 'Login'

        template_values = {
            'user': user,
            'comment': comment,
            'section_name': urllib.quote_plus(section_name),
            'url': url,
            'url_linktext': url_linktext,
         }

         template = JINJA_ENVIRONMENT.get_template('notes.html')
         self.response.write(template.render(template_values))

# [END main_page]

# [START Comment Submission]
class Section(webapp2.RequestHandler):
    def post(self):
        # We set a parent key on the 'Comment' to ensure that they are all
        # in the same entity group. Queries across the single entity group
        # will be consistent.  However, the write rate should be limited to
        # ~1/second. 
        section_name = self.request.get('section_name', DEFAULT_SECTION_NAME)

        comment = Comment(parent=section_key(section_name))

        if users.get_current_user():
            comment.author = Author(
                identity=users.get_current_user().user_id(),
                email=users.get_current_user().email())

        # Get the content from our request parameters, in this case, the message
        # is in the parameter 'content'
        comment.content = self.request.get('content')

        # Write to the Google Database
        comment.put()

        query_params = {'section_name': section_name}
        self.redirect('/?' + urllib.urlencode(query_params))

#[END Comment Submission]


app = webapp2.WSGIApplication([
    ('/', MainPage), 
    ('/section', Section),
], debug=True)

notes.html (an excerpt to test out comment functionality)

<!DOCTYPE html>
{% autoescape true %}
<html>
  <head>
    <meta charset="UTF-8">
    <title>Project Stage 4</title>
  </head>
  <body>
   <h3>User Comments</h3>
   <div>
       <a href="{{ url|safe }}">{{ url_linktext }}</a>

       <form>Section Title:
          <input value="{{ section_name }}" name="section_name">
          <input type="submit" value="switch">
       </form>
       <br><br>

       <form action="/section?section_name={{ section_name }}" method="post">
          <div>
             <label>Comment: <textarea name="content" rows="5" cols="60"></textarea></label>
          </div>
          <input type="submit" value="Submit Comment">
       </form>
       <hr>

       {% for content in comment %}
           {% if comment.content %}
               <b>{{ comment.author.email }}
               {% if user and user.user_id() == comment.author.identity %}
                  (You)
               {% endif %}
               </b> wrote:
           {% else %}
               An anonymous person wrote:
           {% endif %}
           <blockquote>{{ comment.content }}</blockquote>
       {% endfor %}
   </div>
  </body>
</html>
{% endautoescape %}

Answer:

You've confused yourself with the way you've named your variables. You send the list of comments to the template as "comment", then iterate through that using "content" for each item, but then revert back to using "comment" instead.

You should give your things logical names that reflects what they are. In your handler:

comments_query = Comment.query(ancestor=section_key(section_name)).order(-Comment.date)
comments = comments_query.fetch(10)
...
template_values = {
    ...
    'comments': comments,
    ...
 }

and in your template:

{% for comment in comments %}
   {% if comment.content %}
       <b>{{ comment.author.email }}
       ...

Related:


PySerial client unable to write data


python,python-2.7,pyserial
I'm trying to write a python program which can communicate over a serial interface using PySerial module as follows: import serial if __name__ == '__main__': port = "/dev/tnt0" ser = serial.Serial(port, 38400) print ser.name print ser.isOpen() x = ser.write('hello') ser.close() print "Done!" But if I execute the above I get...

monosubstitution cypher : decryption in python 2.7 list trouble


python-2.7
I'm currently coding a simple monosubsubstitution cypher in python. The encryption goes this way: first a key to encypher is produce this way def non_random_key(key_name): my_alphabet = [] for char in alphabet: my_alphabet.append(char) my_key_alphabet = list(key_name) for char in key_name: my_alphabet.remove(char) return my_key_alphabet + my_alphabet Then a message is encrypted...

Anaconda site-packages


python,python-2.7,pip,anaconda
After installing a package in an anaconda environment, I'll like to make some changes to the code in that package. Where can I find the site-packages directory containing the installed packages? I do not find a directory /Users/username/anaconda/lib/python2.7/site-packages...

Keep strings that occur N times or more


python,python-2.7,counter
I have a list that is mylist = ['a', 'a', 'a', 'b', 'b', 'c', 'c', 'd'] And I used Counter from collections on this list to get the result: from collection import Counter counts = Counter(mylist) #Counter({'a': 3, 'c': 2, 'b': 2, 'd': 1}) Now I want to subset this...

Python initialize strings as variable


python,python-2.7
I have a calculation schema as string calc = "((k+m+46)/2)" and some strings containing variable like m = 2 k = m*2 all only strings. Now I want to initialize them into Python. my goal is it to calculate with the calculating schema the varible values. calc should return 26...

I need to make sure that only certain characters are in a list?


python,regex,string,list,python-2.7
I have this to get input and put it in a list: def start(): move_order=[raw_input("Enter your moves: ").split()] And I only want the characters A, D, S, C, H (it's for a game >_>) to be allowed. I've tried using the regular expressions stuff: if re.match('[ADSCH]+', [move_order]) is False: print...

Syntax Error (FROM) in Python, I do not want to use it as function but rather use it as to print something


python,python-2.7
I am trying to print out usernames from Instagram. When I type in print i.from.username, there will be syntax error because Python thinks that I am using from function, which i actually not. for i in a: print i.from.username Is there anyway to troubleshoot it? I tried using making a...

serving GAE applications over http


java,google-app-engine,ssl
I have implemented an application on GAE which can be accessible through https://<my_app_id>.appspot.com. Now I have a custom domain registered with Register.com. As described in GAE documentation I have mapped my custom domain to https://<my_app_id>.appspot.com and I see my application getting served from my custom domain. But I see requests...

Python Popen - wait vs communicate vs CalledProcessError


python,python-2.7,error-handling,popen
Continuing from my previous question I see that to get the error code of a process I spawned via Popen in python I have to call either wait() or communicate() (which can be used to access the Popen stdout and stderr attributes): app7z = '/path/to/7z.exe' command = [app7z, 'a', dstFile.temp,...

Compare 2 seperate csv files and write difference to a new csv file - Python 2.7


python,python-2.7,csv,compare
I am trying to compare two csv files in python and save the difference to a third csv file in python 2.7. import csv f1 = open ("olddata/file1.csv") oldFile1 = csv.reader(f1) oldList1 = [] for row in oldFile1: oldList1.append(row) f2 = open ("newdata/file2.csv") oldFile2 = csv.reader(f2) oldList2 = [] for...

python - how to properly evaluate a value from a system command


python,python-2.7
I'm just learning python (using 2.7.8) and i'm trying to figure out what is the best way to evaluate the output of a system command. I've read to use subprocess. For example, I need to run this IF statment and evaluate for anything > 0, then process it. Example of...

How do I copy a row from one pandas dataframe to another pandas dataframe?


python,python-2.7,pandas,dataframes
I have a dataframe of data that I am trying to append to another dataframe. I have tried various ways with .append() and there has been no successful way. When I print the data from iterrows. I provide 2 possible ways I tried to solve the issue below, one creates...

Getting user credentials using Google+ API


android,google-app-engine,google-api,google-api-java-client
I am trying to include Google sign in in my android application using Google+ Api. I am able to take account details from the user but once signed in I am getting null when requesting for username using call: Plus.PeopleApi.getCurrentPerson(mGoogleApiClient).getDisplayName() And Logcat shows: BasicNetwork.performRequest: Unexpected response code 403 for https://www.googleapis.com/plus/v1/people/me...

how to fetch a column in browse_record_list in orm browse method in openERP


python-2.7,orm,openerp-7
I'm beginner in openERP. I'm trying to get a column in a table. While using ORM browse method and iterating that object i got the result in browse_record_list as browse_record(table.name,21). I want to fetch that particular id 21 alone through that browse method but instead im getting same browse_record as...

Use NamedTemporaryFile to read from stdout via subprocess on Linux


python-2.7,subprocess,temporary-files
import subprocess import tempfile fd = tempfile.NamedTemporaryFile() print(fd) print(fd.name) p = subprocess.Popen("date", stdout=fd).communicate() print(p[0]) fd.close() This returns: <open file '<fdopen>', mode 'w' at 0x7fc27eb1e810> /tmp/tmp8kX9C1 None Instead, I would like it to return something like: Tue Jun 23 10:23:15 CEST 2015 I tried adding mode="w", as well as delete=False, but...

Parsing Google Custom Search API for Elasticsearch Documents


json,python-2.7,elasticsearch,google-search-api
After retrieving results from the Google Custom Search API and writing it to JSON, I want to parse that JSON to make valid Elasticsearch documents. You can configure a parent - child relationship for nested results. However, this relationship seems to not be inferred by the data structure itself. I've...

Stopping list selection in Python 2.7


python,list,python-2.7
Imagine that I have an order list of tuples: s = [(0,-1), (1,0), (2,-1), (3,0), (4,0), (5,-1), (6,0), (7,-1)] Given a parameter X, I want to select all the tuples that have a first element equal or greater than X up to but not including the first tuple that has...

Python root logger messages not being logged via handler configured with fileConfig


python,python-2.7,logging,configuration-files
The Problem: Given a logging config and a logger that employs that config, I see log messages from the script in which the log handler is configured, but not from the root logger, to which the same handler is assigned. Details: (Using Python 2.7) I have a module my_mod which...

What is the difference between <> and == in python?


python-2.7
In [142]: (MON,TUE,WED,THR,FRI,SAT,SUN)<>range(7) Out[142]: True In [143]: (MON,TUE,WED,THR,FRI,SAT,SUN)==range(7) Out[143]: False ...

How to skip a function


function,python-2.7
I am learning python and trying to make a little game. So my question is can you define a function but skip it and use it later. EX. def func() print"1,2,3,4" func() def func2() print "counting" func() func2() How would I skip func but still be able to print it...

Need workaround to treat float values as tuples when updating “list” of float values


python-2.7,matplotlib,computer-science,floating-point-conversion
I am finding errors with the last line of the for loop where I am trying to update the curve value to a list containing the curve value iterations. I get errors like "can only concatenate tuple (not "float) to tuple" and "tuple object has no attribute 'append'". Does anyone...

IllegalArgumentException: expected primitive class, but got: class UUID


android,google-app-engine,google-cloud-endpoints
My app is using GAE endpoints. My model has UUID. And once i try to send it Android app it encounters illegalArgument exception. Anyone has got recommendations how to handle endpoints model with UUID on android app with Google App Engine endpoints? 06-14 23:26:49.560 27462-27488/com.example E/AndroidRuntime﹕ FATAL EXCEPTION: AsyncTask #1...

lookbehind for start of string or a character


regex,python-2.7,regex-lookarounds
The command re.compile(ur"(?<=,| |^)(?:next to|near|beside|opp).+?(?=,|$)", re.IGNORECASE) throws a sre_constants.error: look-behind requires fixed-width pattern error in my program but regex101 shows it to be fine. What I'm trying to do here is to match landmarks from addresses (each address is in a separate string) like: "Opp foobar, foocity" --> Must match...

Python - Terminate Child Process or PID?


python-2.7
I have a script (simplified below) that initiates another python process. I know the process name and PID for the current and child processes. When I attempt to terminate the child process - menu option (2) - I get the message "local variable 'py_process' referenced before assignment." Suggestions to terminate...

multiple iteration of the same list


python,python-2.7,python-3.x,numpy,shapely
I have one list of data as follows: from shapely.geometry import box data = [box(1,2,3,4), box(4,5,6,7), box(1,2,3,4)] sublists = [A,B,C] The list 'data' has following sub-lists: A = box(1,2,3,4) B = box(4,5,6,7) C = box(1,2,3,4) I have to check if sub-lists intersect. If intersect they should put in one tuple;...

Pass function call as a function argument


python,python-2.7,python-3.x
Code: def function1(a,b): return a-1,b-1 def function2(c,d): return c+1,d+1 print function1(function2(1,2)) Error: Traceback (most recent call last): File "C:\Users\sony\Desktop\Python\scripts\twitter_get_data.py", line 6, in <module> print function1(function2(1,2)) TypeError: function1() takes exactly 2 arguments (1 given) [Finished in 0.1s with exit code 1] Why the above error? ...

Adding time/duration from CSV file


python,python-2.7,csv,datetime
I am trying to add time/duration values from a CSV file that I have but I have failed so far. Here's the sample csv that I'm trying to add up. Is getting this output possible? Output: I have been trying to add up the datetime but I always fail: finput...

How can I resolve my variable's unexpected output?


django,python-2.7
I have a variable in django named optional_message. If I debug the variable then it says Swenskt but when I try to print the variable on my page the following comes out: (u'Swenskt',) and the variable can't be tested for its length etc. What should I do if I only...

How to extract efficientely content from an xml with python?


python,xml,python-2.7,pandas,lxml
I have the following xml: <?xml version="1.0" encoding="UTF-8" standalone="no"?><author id="user23"> <document><![CDATA["@username: That boner came at the wrong time ???? http://t.co/5X34233gDyCaCjR" HELP I'M DYING ]]></document> <document><![CDATA[Ugh ]]></document> <document><![CDATA[YES !!!! WE GO FOR IT. http://t.co/fiI23324E83b0Rt ]]></document> <document><![CDATA[@username Shout out to me???? ]]></document> </author> What is the most efficient...

from x(defined in program) import y(defined in program) python


python,python-2.7,import,filenames
I need some assitance since I really have no idea how I can fix this: x="test" y="test2" When I try to import y from x , it says that there is no file with the name "x" (from x import y) Is there any way to import test2 from test...

delete data from mysql table based on multiple conditions


php,mysql,python-2.7
i need to delete rows from MySQL table which is very huge.I have multiple conditions check before deleting the data. my table looks like: data(table name): name mobile email address source xyz 871 [email protected] 1.txt bac 123 null 2.XLS TST 456 [email protected] 3.xls yup 897 null abcde web null [email protected]

Count function counting only last line of my list


python,python-2.7
Count function counting only last line of my list N = int(raw_input()) cnt = [] for i in range(N): string = raw_input() for j in range(1,len(string)): if string[j] =='K': cnt.append('R') elif string[j] =='R': cnt.append('R') if string[0] == 'k': cnt.append('k') elif string[0] == 'R': cnt.append('R') print cnt.count('R') if I am giving...

Benefit of using os.mkdir vs os.system(“mkdir”)


python,python-2.7
Simple question that I can't find an answer to: Is there a benefit of using os.mkdir("somedir") over os.system("mkdir somedir") or subprocess.call(), beyond code portability? Answers should apply to Python 2.7. Edit: the point was raised that a hard-coded directory versus a variable (possibly containing user-defined data) introduces the question of...

Import on class instanciation


python,python-2.7
I'm creating a module with several classes in it. My problem is that some of these classes need to import very specific modules that needs to be manually compiled or need specific hardware to work. There is no interest in importing every specific module up front, and as some modules...

Is there a way to say for every x values, do this?


python,python-2.7
Before I start, I am new to Python, so any low-level description would be incredibly helpful! I have a list of lets say 60 values (representing one hour, from 8:00-9:00) and I want to run average, maximums, minimums, and standard deviation for each set of 15. (I already have the...

How to check for multiple attributes in a list


python,python-2.7
I am making a TBRPG game using Python 2.7, and i'm currently making a quest system. I wanted to make a function that checks all of the quests in a list, in this case (quests), and tells you if any of of the quests in the list have the same...

List of tuples from (a, all b) to (b, all a)


python,list,python-2.7,tuples
I am starting with a list of tuples (a,all b). I want to end with a list of tuples (b,all a). For example: FROM (a1,[b1,b2,b3]) (a2,[b2]) (a3,[b1,b2]) TO (b1,[a1,a3]) (b2[a1,a2,a3]) (b3,[a1] How do I do this using Python 2? Thank you for your help....

How to remove structure with python from this case?
python,python-2.7
How to remove "table" from HTML using python? I had case like this: paragraph = ''' <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Quidem molestiae consequuntur officiis corporis sint.<br /><br /> <table> <tr> <td> text title </td> <td> text title 2 </td> </tr> </table> <p> lorem ipsum</p> ''' how...

Pandas Dataframe Complex Calculation


python,python-2.7,pandas,dataframes
I have the following dataframe,df: Year totalPubs ActualCitations 0 1994 71 191.002034 1 1995 77 2763.911781 2 1996 69 2022.374474 3 1997 78 3393.094951 I want to write code that would do the following: Citations of currentyear / Sum of totalPubs of the two previous years I want something to...

Identify that a string could be a datetime object


python,regex,algorithm,python-2.7,datetime
If I knew the format in which a string represents date-time information, then I can easily use datetime.datetime.strptime(s, fmt). However, without knowing the format of the string beforehand, would it be possible to determine whether a given string contains something that could be parsed as a datetime object with the...

Python split by comma delimiter and strip


python,python-2.7
I am trying to open a file in python in read mode then write striped and split data to an output file. I am unsure how to split and strip the same data. Do I need to create a different line? Do I need to write the data out first?...

Google App Engine datastore: filter()


python,google-app-engine
I'm trying to retrieve an entry from Google App Engine's datastore using the filter() method as follows: result = Sender.all().filter("email =", email).filter("source_address =", source).filter("dest_address =", dest).filter("food_type =", food_type) Then, if such an entry exists, I change the value of one of the columns in that entry. Otherwise, I'm displaying an...

Who calls the metaclass


python,python-2.7,metaclass
This actually stems from a discussion here on SO. Short version def meta(name, bases, class_dict) return type(name, bases, class_dict) class Klass(object): __metaclass__ = meta meta() is called when Klass class declaration is executed. Which part of the (python internal) code actually calls meta()? Long version When the class is declared,...

Sending mail by Unauthorised sender in Google AppEngine


python,google-app-engine,email,sendmail
I've got a Google AppEngine Python application connected with my domain. I want to be able to send emails from any email, like: [email protected] So I use sendmail() and set mailobject.sender = "[email protected]", but it does not work. Also I made a receive function, but I don't want to receive...

Strange Behavior: Floating Point Error after Appending to List


python,python-2.7,behavior
I am writing a simple function to step through a range with floating step size. To keep the output neat, I wrote a function, correct, that corrects the floating point error that is common after an arithmetic operation. That is to say: correct(0.3999999999) outputs 0.4, correct(0.1000000001) outputs 0.1, etc. Here's...

Why does `for lst in lst:` work? [duplicate]


python,python-2.7
This question already has an answer here: Why can I use the same name for iterator and sequence in a Python for loop? 6 answers The following code lst = ['foo', 'bar', 'baz'] for lst in lst: print lst gives me this output foo bar baz I would expect...

Slicing a Python OrderedDict


python-2.7,slice,ordereddictionary
In my code I frequently need to take a subset range of keys+values from a Python OrderedDict (from collections package). Slicing doesn't work (throws TypeError: unhashable type) and the alternative, iterating, is cumbersome: from collections import OrderedDict o = OrderedDict([('a', 1), ('b', 2), ('c', 3), ('d', 4)]) # want to...

Sort List of Numbers according to Custom Number Sequence


list,python-2.7,sorting
Question :A set of numbers will be passed as input. Also the redefined relationship of the digits 0-9 in ascending order will be passed as input. Based on the redefined relationship, the set of numbers must be listed in ascending order. Input Format: The first line will contain the the...

Parse text from a .txt file using csv module


python,python-2.7,parsing,csv
I have an email that comes in everyday and the format of the email is always the same except some of the data is different. I wrote a VBA Macro that exports the email to a text file. Now that it is a text file I want to parse the...

Python code not executing in order? MySQLdb UPDATE commits in unexpected order


python,python-2.7,threadpool,mysql-python
I've got a Python 2.7 script I'm working on that retrieves rows from a MySQL table, loops through the data to process it, then is supposed to do the following things in this order: UPDATE the table rows we just got previously to set a locked value in each row...