Whitespace and formatting cleanup.

* Removed trailing whitespace
* Line length < 80 where possible
* Honor conventions on number of blank lines
* Honor conventions about spaces around :, =
This commit is contained in:
Nathan Yergler 2011-10-01 15:10:02 -07:00
parent 573aba86b5
commit 243c3843bd
38 changed files with 135 additions and 113 deletions

View File

@ -101,7 +101,6 @@ class MediaGoblinApp(object):
self.middleware = [util.import_component(m)(self) self.middleware = [util.import_component(m)(self)
for m in middleware.ENABLED_MIDDLEWARE] for m in middleware.ENABLED_MIDDLEWARE]
def __call__(self, environ, start_response): def __call__(self, environ, start_response):
request = Request(environ) request = Request(environ)

View File

@ -61,7 +61,8 @@ class ForgotPassForm(wtforms.Form):
def validate_username(form, field): def validate_username(form, field):
if not (re.match(r'^\w+$', field.data) or if not (re.match(r'^\w+$', field.data) or
re.match(r'^.+@[^.].*\.[a-z]{2,10}$',field.data, re.IGNORECASE)): re.match(r'^.+@[^.].*\.[a-z]{2,10}$', field.data,
re.IGNORECASE)):
raise wtforms.ValidationError(u'Incorrect input') raise wtforms.ValidationError(u'Incorrect input')
@ -82,4 +83,3 @@ class ChangePassForm(wtforms.Form):
token = wtforms.HiddenField( token = wtforms.HiddenField(
'', '',
[wtforms.validators.Required()]) [wtforms.validators.Required()])

View File

@ -93,6 +93,7 @@ EMAIL_VERIFICATION_TEMPLATE = (
u"http://{host}{uri}?" u"http://{host}{uri}?"
u"userid={userid}&token={verification_key}") u"userid={userid}&token={verification_key}")
def send_verification_email(user, request): def send_verification_email(user, request):
""" """
Send the verification email to users to activate their accounts. Send the verification email to users to activate their accounts.
@ -127,6 +128,7 @@ EMAIL_FP_VERIFICATION_TEMPLATE = (
u"http://{host}{uri}?" u"http://{host}{uri}?"
u"userid={userid}&token={fp_verification_key}") u"userid={userid}&token={fp_verification_key}")
def send_fp_verification_email(user, request): def send_fp_verification_email(user, request):
""" """
Send the verification email to users to change their password. Send the verification email to users to change their password.
@ -150,4 +152,3 @@ def send_fp_verification_email(user, request):
[user['email']], [user['email']],
'GNU MediaGoblin - Change forgotten password!', 'GNU MediaGoblin - Change forgotten password!',
rendered_email) rendered_email)

View File

@ -33,7 +33,8 @@ auth_routes = [
controller='mediagoblin.views:simple_template_render'), controller='mediagoblin.views:simple_template_render'),
Route('mediagoblin.auth.forgot_password', '/forgot_password/', Route('mediagoblin.auth.forgot_password', '/forgot_password/',
controller='mediagoblin.auth.views:forgot_password'), controller='mediagoblin.auth.views:forgot_password'),
Route('mediagoblin.auth.verify_forgot_password', '/forgot_password/verify/', Route('mediagoblin.auth.verify_forgot_password',
'/forgot_password/verify/',
controller='mediagoblin.auth.views:verify_forgot_password'), controller='mediagoblin.auth.views:verify_forgot_password'),
Route('mediagoblin.auth.fp_changed_success', Route('mediagoblin.auth.fp_changed_success',
'/forgot_password/changed_success/', '/forgot_password/changed_success/',

View File

@ -233,8 +233,7 @@ def forgot_password(request):
request, 'mediagoblin.user_pages.user_home', request, 'mediagoblin.user_pages.user_home',
user=user['username']) user=user['username'])
# do not reveal whether or not there is a matching user
# do not reveal whether or not there is a matching user, just move along
return redirect(request, 'mediagoblin.auth.fp_email_sent') return redirect(request, 'mediagoblin.auth.fp_email_sent')
return render_to_response( return render_to_response(

View File

@ -93,8 +93,9 @@ MEDIAENTRY_INDEXES = {
('created', DESCENDING)]}, ('created', DESCENDING)]},
'state_uploader_tags_created': { 'state_uploader_tags_created': {
# Indexing on processed?, media uploader, associated tags, and timestamp # Indexing on processed?, media uploader, associated tags, and
# Used for showing media items matching a tag search, most recent first. # timestamp Used for showing media items matching a tag
# search, most recent first.
'index': [('state', ASCENDING), 'index': [('state', ASCENDING),
('uploader', ASCENDING), ('uploader', ASCENDING),
('tags.slug', DESCENDING), ('tags.slug', DESCENDING),

View File

@ -14,7 +14,8 @@
# You should have received a copy of the GNU Affero General Public License # You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>. # along with this program. If not, see <http://www.gnu.org/licenses/>.
import datetime, uuid import datetime
import uuid
from mongokit import Document from mongokit import Document
@ -79,7 +80,7 @@ class User(Document):
'bio': unicode, # May contain markdown 'bio': unicode, # May contain markdown
'bio_html': unicode, # May contain plaintext, or HTML 'bio_html': unicode, # May contain plaintext, or HTML
'fp_verification_key': unicode, # forgotten password verification key 'fp_verification_key': unicode, # forgotten password verification key
'fp_token_expire': datetime.datetime 'fp_token_expire': datetime.datetime,
} }
required_fields = ['username', 'created', 'pw_hash', 'email'] required_fields = ['username', 'created', 'pw_hash', 'email']
@ -220,7 +221,8 @@ class MediaEntry(Document):
return self.db.MediaComment.find({ return self.db.MediaComment.find({
'media_entry': self['_id']}).sort('created', DESCENDING) 'media_entry': self['_id']}).sort('created', DESCENDING)
def get_display_media(self, media_map, fetch_order=DISPLAY_IMAGE_FETCHING_ORDER): def get_display_media(self, media_map,
fetch_order=DISPLAY_IMAGE_FETCHING_ORDER):
""" """
Find the best media for display. Find the best media for display.
@ -353,4 +355,3 @@ def register_models(connection):
Register all models in REGISTER_MODELS with this connection. Register all models in REGISTER_MODELS with this connection.
""" """
connection.register(REGISTER_MODELS) connection.register(REGISTER_MODELS)

View File

@ -122,7 +122,8 @@ def remove_deprecated_indexes(database, deprecated_indexes=DEPRECATED_INDEXES):
# Don't set this yourself! RegisterMigration will automatically fill # Don't set this yourself! RegisterMigration will automatically fill
# this with stuff via decorating methods in migrations.py # this with stuff via decorating methods in migrations.py
class MissingCurrentMigration(Exception): pass class MissingCurrentMigration(Exception):
pass
MIGRATIONS = {} MIGRATIONS = {}

View File

@ -119,6 +119,7 @@ def get_user_media_entry(controller):
return _make_safe(wrapper, controller) return _make_safe(wrapper, controller)
def get_media_entry_by_id(controller): def get_media_entry_by_id(controller):
""" """
Pass in a MediaEntry based off of a url component Pass in a MediaEntry based off of a url component
@ -138,4 +139,3 @@ def get_media_entry_by_id(controller):
return controller(request, media=media, *args, **kwargs) return controller(request, media=media, *args, **kwargs)
return _make_safe(wrapper, controller) return _make_safe(wrapper, controller)

View File

@ -13,5 +13,3 @@
# #
# You should have received a copy of the GNU Affero General Public License # You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>. # along with this program. If not, see <http://www.gnu.org/licenses/>.

View File

@ -119,7 +119,7 @@ def edit_attachments(request, media):
name=request.POST['attachment_name'] \ name=request.POST['attachment_name'] \
or request.POST['attachment_file'].filename, or request.POST['attachment_file'].filename,
filepath=attachment_public_filepath, filepath=attachment_public_filepath,
created=datetime.utcnow() created=datetime.utcnow(),
)) ))
media.save() media.save()

View File

@ -80,4 +80,3 @@ def main_cli():
if __name__ == '__main__': if __name__ == '__main__':
main_cli() main_cli()

View File

@ -229,7 +229,8 @@ def env_export(args):
''' '''
if args.cache_path: if args.cache_path:
if os.path.exists(args.cache_path): if os.path.exists(args.cache_path):
_log.error('The cache directory must not exist before you run this script') _log.error('The cache directory must not exist '
'before you run this script')
_log.error('Cache directory: {0}'.format(args.cache_path)) _log.error('Cache directory: {0}'.format(args.cache_path))
return False return False

View File

@ -41,7 +41,7 @@ def adduser(args):
db = mg_globals.database db = mg_globals.database
users_with_username = \ users_with_username = \
db.User.find({ db.User.find({
'username': args.username.lower() 'username': args.username.lower(),
}).count() }).count()
if users_with_username: if users_with_username:
@ -107,4 +107,3 @@ def changepw(args):
print 'Password successfully changed' print 'Password successfully changed'
else: else:
print 'The user doesn\'t exist' print 'The user doesn\'t exist'

View File

@ -29,8 +29,12 @@ from mediagoblin.workbench import WorkbenchManager
from mediagoblin.storage import storage_system_from_config from mediagoblin.storage import storage_system_from_config
class Error(Exception): pass class Error(Exception):
class ImproperlyConfigured(Error): pass pass
class ImproperlyConfigured(Error):
pass
def setup_global_and_app_config(config_path): def setup_global_and_app_config(config_path):

View File

@ -25,4 +25,3 @@ tag_routes = [
Route('mediagoblin.listings.tag_atom_feed', "/{tag}/atom/", Route('mediagoblin.listings.tag_atom_feed', "/{tag}/atom/",
controller="mediagoblin.listings.views:tag_atom_feed"), controller="mediagoblin.listings.views:tag_atom_feed"),
] ]

View File

@ -63,6 +63,7 @@ def tag_listing(request, page):
ATOM_DEFAULT_NR_OF_UPDATED_ITEMS = 15 ATOM_DEFAULT_NR_OF_UPDATED_ITEMS = 15
def tag_atom_feed(request): def tag_atom_feed(request):
""" """
generates the atom feed with the tag images generates the atom feed with the tag images

View File

@ -20,11 +20,13 @@ SUCCESS = 'success'
WARNING = 'warning' WARNING = 'warning'
ERROR = 'error' ERROR = 'error'
def add_message(request, level, text): def add_message(request, level, text):
messages = request.session.setdefault('messages', []) messages = request.session.setdefault('messages', [])
messages.append({'level': level, 'text': text}) messages.append({'level': level, 'text': text})
request.session.save() request.session.save()
def fetch_messages(request, clear_from_session=True): def fetch_messages(request, clear_from_session=True):
messages = request.session.get('messages') messages = request.session.get('messages')
if messages and clear_from_session: if messages and clear_from_session:

View File

@ -14,6 +14,7 @@
# You should have received a copy of the GNU Affero General Public License # You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>. # along with this program. If not, see <http://www.gnu.org/licenses/>.
class NoOpMiddleware(object): class NoOpMiddleware(object):
def __init__(self, mg_app): def __init__(self, mg_app):

View File

@ -65,9 +65,10 @@ class ProcessMedia(Task):
""" """
If the processing failed we should mark that in the database. If the processing failed we should mark that in the database.
Assuming that the exception raised is a subclass of BaseProcessingFail, Assuming that the exception raised is a subclass of
we can use that to get more information about the failure and store that BaseProcessingFail, we can use that to get more information
for conveying information to users about the failure, etc. about the failure and store that for conveying information to
users about the failure, etc.
""" """
entry_id = args[0] entry_id = args[0]
mark_entry_failed(entry_id, exc) mark_entry_failed(entry_id, exc)
@ -80,10 +81,10 @@ def mark_entry_failed(entry_id, exc):
""" """
Mark a media entry as having failed in its conversion. Mark a media entry as having failed in its conversion.
Uses the exception that was raised to mark more information. If the Uses the exception that was raised to mark more information. If
exception is a derivative of BaseProcessingFail then we can store extra the exception is a derivative of BaseProcessingFail then we can
information that can be useful for users telling them why their media failed store extra information that can be useful for users telling them
to process. why their media failed to process.
Args: Args:
- entry_id: The id of the media entry - entry_id: The id of the media entry
@ -164,7 +165,8 @@ def process_image(entry):
with queued_file: with queued_file:
original_filepath = create_pub_filepath(entry, queued_filepath[-1]) original_filepath = create_pub_filepath(entry, queued_filepath[-1])
with mgg.public_store.get_file(original_filepath, 'wb') as original_file: with mgg.public_store.get_file(original_filepath, 'wb') \
as original_file:
original_file.write(queued_file.read()) original_file.write(queued_file.read())
mgg.queue_store.delete_file(queued_filepath) mgg.queue_store.delete_file(queued_filepath)

View File

@ -16,6 +16,7 @@
from mediagoblin.util import lazy_pass_to_ugettext as _ from mediagoblin.util import lazy_pass_to_ugettext as _
class BaseProcessingFail(Exception): class BaseProcessingFail(Exception):
""" """
Base exception that all other processing failure messages should Base exception that all other processing failure messages should

View File

@ -27,6 +27,7 @@ from mediagoblin.storage import StorageInterface, clean_listy_filepath
import cloudfiles import cloudfiles
import mimetypes import mimetypes
class CloudFilesStorage(StorageInterface): class CloudFilesStorage(StorageInterface):
''' '''
OpenStack/Rackspace Cloud's Swift/CloudFiles support OpenStack/Rackspace Cloud's Swift/CloudFiles support

View File

@ -13,5 +13,3 @@
# #
# You should have received a copy of the GNU Affero General Public License # You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>. # along with this program. If not, see <http://www.gnu.org/licenses/>.

View File

@ -16,9 +16,9 @@
from mimetypes import guess_type from mimetypes import guess_type
ALLOWED = ['image/jpeg', 'image/png', 'image/tiff', 'image/gif'] ALLOWED = ['image/jpeg', 'image/png', 'image/tiff', 'image/gif']
def check_filetype(posted_file): def check_filetype(posted_file):
if not guess_type(posted_file.filename)[0] in ALLOWED: if not guess_type(posted_file.filename)[0] in ALLOWED:
return False return False

View File

@ -90,8 +90,10 @@ def submit_start(request):
# We generate this ourselves so we know what the taks id is for # We generate this ourselves so we know what the taks id is for
# retrieval later. # retrieval later.
# (If we got it off the task's auto-generation, there'd be a risk of
# a race condition when we'd save after sending off the task) # (If we got it off the task's auto-generation, there'd be
# a risk of a race condition when we'd save after sending
# off the task)
task_id = unicode(uuid.uuid4()) task_id = unicode(uuid.uuid4())
entry['queued_task_id'] = task_id entry['queued_task_id'] = task_id
@ -113,8 +115,8 @@ def submit_start(request):
# expect a lot of users to run things in this way we have to # expect a lot of users to run things in this way we have to
# capture stuff here. # capture stuff here.
# #
# ... not completely the diaper pattern because the exception is # ... not completely the diaper pattern because the
# re-raised :) # exception is re-raised :)
mark_entry_failed(entry[u'_id'], exc) mark_entry_failed(entry[u'_id'], exc)
# re-raise the exception # re-raise the exception
raise raise

View File

@ -13,5 +13,3 @@
# #
# You should have received a copy of the GNU Affero General Public License # You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>. # along with this program. If not, see <http://www.gnu.org/licenses/>.

View File

@ -66,6 +66,7 @@ def user_home(request, page):
'media_entries': media_entries, 'media_entries': media_entries,
'pagination': pagination}) 'pagination': pagination})
@uses_pagination @uses_pagination
def user_gallery(request, page): def user_gallery(request, page):
"""'Gallery' of a User()""" """'Gallery' of a User()"""
@ -95,6 +96,7 @@ def user_gallery(request, page):
MEDIA_COMMENTS_PER_PAGE = 50 MEDIA_COMMENTS_PER_PAGE = 50
@get_user_media_entry @get_user_media_entry
@uses_pagination @uses_pagination
def media_home(request, media, page, **kwargs): def media_home(request, media, page, **kwargs):
@ -184,6 +186,7 @@ def media_confirm_delete(request, media):
ATOM_DEFAULT_NR_OF_UPDATED_ITEMS = 15 ATOM_DEFAULT_NR_OF_UPDATED_ITEMS = 15
def atom_feed(request): def atom_feed(request):
""" """
generates the atom feed with the newest images generates the atom feed with the newest images

View File

@ -45,6 +45,8 @@ from itertools import izip, count
DISPLAY_IMAGE_FETCHING_ORDER = [u'medium', u'original', u'thumb'] DISPLAY_IMAGE_FETCHING_ORDER = [u'medium', u'original', u'thumb']
TESTS_ENABLED = False TESTS_ENABLED = False
def _activate_testing(): def _activate_testing():
""" """
Call this to activate testing in util.py Call this to activate testing in util.py
@ -197,6 +199,7 @@ def import_component(import_string):
_punct_re = re.compile(r'[\t !"#$%&\'()*\-/<=>?@\[\\\]^_`{|},.]+') _punct_re = re.compile(r'[\t !"#$%&\'()*\-/<=>?@\[\\\]^_`{|},.]+')
def slugify(text, delim=u'-'): def slugify(text, delim=u'-'):
""" """
Generates an ASCII-only slug. Taken from http://flask.pocoo.org/snippets/5/ Generates an ASCII-only slug. Taken from http://flask.pocoo.org/snippets/5/
@ -253,6 +256,7 @@ class FakeMhost(object):
'to': to_addrs, 'to': to_addrs,
'message': message}) 'message': message})
def _clear_test_inboxes(): def _clear_test_inboxes():
global EMAIL_TEST_INBOX global EMAIL_TEST_INBOX
global EMAIL_TEST_MBOX_INBOX global EMAIL_TEST_MBOX_INBOX
@ -263,6 +267,7 @@ def _clear_test_inboxes():
### </Special email test stuff> ### </Special email test stuff>
### ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ### ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
def send_email(from_addr, to_addrs, subject, message_body): def send_email(from_addr, to_addrs, subject, message_body):
""" """
Simple email sending wrapper, use this so we can capture messages Simple email sending wrapper, use this so we can capture messages
@ -443,6 +448,7 @@ def media_tags_as_string(media_entry_tags):
TOO_LONG_TAG_WARNING = \ TOO_LONG_TAG_WARNING = \
u'Tags must be shorter than %s characters. Tags that are too long: %s' u'Tags must be shorter than %s characters. Tags that are too long: %s'
def tag_length_validator(form, field): def tag_length_validator(form, field):
""" """
Make sure tags do not exceed the maximum tag length. Make sure tags do not exceed the maximum tag length.
@ -460,6 +466,7 @@ def tag_length_validator(form, field):
MARKDOWN_INSTANCE = markdown.Markdown(safe_mode='escape') MARKDOWN_INSTANCE = markdown.Markdown(safe_mode='escape')
def cleaned_markdown_conversion(text): def cleaned_markdown_conversion(text):
""" """
Take a block of text, run it through MarkDown, and clean its HTML. Take a block of text, run it through MarkDown, and clean its HTML.
@ -474,6 +481,7 @@ def cleaned_markdown_conversion(text):
SETUP_GETTEXTS = {} SETUP_GETTEXTS = {}
def setup_gettext(locale): def setup_gettext(locale):
""" """
Setup the gettext instance based on this locale Setup the gettext instance based on this locale
@ -558,6 +566,7 @@ def fake_ugettext_passthrough(string):
PAGINATION_DEFAULT_PER_PAGE = 30 PAGINATION_DEFAULT_PER_PAGE = 30
class Pagination(object): class Pagination(object):
""" """
Pagination class for mongodb queries. Pagination class for mongodb queries.
@ -575,8 +584,8 @@ class Pagination(object):
- page: requested page - page: requested page
- per_page: number of objects per page - per_page: number of objects per page
- cursor: db cursor - cursor: db cursor
- jump_to_id: ObjectId, sets the page to the page containing the object - jump_to_id: ObjectId, sets the page to the page containing the
with _id == jump_to_id. object with _id == jump_to_id.
""" """
self.page = page self.page = page
self.per_page = per_page self.per_page = per_page
@ -594,7 +603,6 @@ class Pagination(object):
self.active_id = jump_to_id self.active_id = jump_to_id
break break
def __call__(self): def __call__(self):
""" """
Returns slice of objects for the requested page Returns slice of objects for the requested page
@ -628,8 +636,7 @@ class Pagination(object):
last = num last = num
def get_page_url_explicit(self, base_url, get_params, page_no): def get_page_url_explicit(self, base_url, get_params, page_no):
""" """Get a page url by adding a page= parameter to the base url
Get a page url by adding a page= parameter to the base url
""" """
new_get_params = copy.copy(get_params or {}) new_get_params = copy.copy(get_params or {})
new_get_params['page'] = page_no new_get_params['page'] = page_no
@ -637,8 +644,7 @@ class Pagination(object):
base_url, urllib.urlencode(new_get_params)) base_url, urllib.urlencode(new_get_params))
def get_page_url(self, request, page_no): def get_page_url(self, request, page_no):
""" """Get a new page url based of the request, and the new page number.
Get a new page url based of the request, and the new page number.
This is a nice wrapper around get_page_url_explicit() This is a nice wrapper around get_page_url_explicit()
""" """
@ -682,6 +688,7 @@ def render_404(request):
return render_to_response( return render_to_response(
request, 'mediagoblin/404.html', {}, status=400) request, 'mediagoblin/404.html', {}, status=400)
def delete_media_files(media): def delete_media_files(media):
""" """
Delete all files associated with a MediaEntry Delete all files associated with a MediaEntry

View File

@ -19,6 +19,7 @@ from mediagoblin.util import render_to_response, Pagination
from mediagoblin.db.util import DESCENDING from mediagoblin.db.util import DESCENDING
from mediagoblin.decorators import uses_pagination from mediagoblin.decorators import uses_pagination
@uses_pagination @uses_pagination
def root_view(request, page): def root_view(request, page):
cursor = request.db.MediaEntry.find( cursor = request.db.MediaEntry.find(

View File

@ -42,8 +42,10 @@ class Workbench(object):
def __unicode__(self): def __unicode__(self):
return unicode(self.dir) return unicode(self.dir)
def __str__(self): def __str__(self):
return str(self.dir) return str(self.dir)
def __repr__(self): def __repr__(self):
return repr(self.dir) return repr(self.dir)

View File

@ -29,7 +29,8 @@ def get_version():
if mo: if mo:
return mo.group(1) return mo.group(1)
else: else:
raise RuntimeError("Unable to find version string in %s." % VERSIONFILE) raise RuntimeError("Unable to find version string in %s." %
VERSIONFILE)
setup( setup(
@ -83,7 +84,6 @@ setup(
[babel.extractors] [babel.extractors]
jinja2 = jinja2.ext:babel_extract jinja2 = jinja2.ext:babel_extract
""", """,
license='AGPLv3', license='AGPLv3',
author='Free Software Foundation and contributors', author='Free Software Foundation and contributors',
author_email='cwebber@gnu.org', author_email='cwebber@gnu.org',