python - Django Error: TypeError: expected string or buffer -


i'm writing code django-based static blog, coming across similar issue across 3 or 4 different areas of code. figured if can 1 fixed can others fixed well. code of focus django-command call update_blog1. here's traceback...

traceback (most recent call last):   file "c:\python34\lib\site-packages\django\core\handlers\base.py", line 132, in get_response response = wrapped_callback(request, *callback_args, **callback_kwargs)   file "c:/users/jaysp_000/firstsite/projectone\blog_static\views.py", line 179, in archive {'posts' : posts}   file "c:/users/jaysp_000/firstsite/projectone\blog_static\views.py", line 14, in render_response return render_to_response(*args, **kwargs)   file "c:\python34\lib\site-packages\django\shortcuts.py", line 45, in render_to_response using=using)   file "c:\python34\lib\site-packages\django\template\loader.py", line 116, in render_to_string template_name, context, context_instance, dirs, dictionary)   file "c:\python34\lib\site-packages\django\template\engine.py", line 221, in render_to_string return t.render(context_instance)   file "c:\python34\lib\site-packages\django\template\base.py", line 208, in render context.bind_template(self):   file "c:\python34\lib\contextlib.py", line 59, in __enter__ return next(self.gen)   file "c:\python34\lib\site-packages\django\template\context.py", line 235, in bind_template updates.update(processor(self.request))   file "c:\python34\lib\site-packages\django\template\context_processors.py", line 56, in i18n context_extras['language_bidi'] = translation.get_language_bidi()   file "c:\python34\lib\site-packages\django\utils\translation\__init__.py", line 177, in get_language_bidi return _trans.get_language_bidi()  file "c:\python34\lib\site-packages\django\utils\translation\trans_real.py", line 263, in get_language_bidi base_lang = get_language().split('-')[0] attributeerror: 'nonetype' object has no attribute 'split'   during handling of above exception, exception occurred:   traceback (most recent call last):   file "c:\python34\lib\site-packages\django\utils\formats.py", line 103, in get_format cached = _format_cache[cache_key] keyerror: ('r', none)  during handling of above exception, exception occurred:  traceback (most recent call last):   file "c:\program files (x86)\jetbrains\pycharm 4.5.3\helpers\pycharm\django_manage.py", line 41, in <module> run_module(manage_file, none, '__main__', true)   file "c:\python34\lib\runpy.py", line 182, in run_module return _run_module_code(code, init_globals, run_name, mod_spec)   file "c:\python34\lib\runpy.py", line 96, in _run_module_code mod_name, mod_spec, pkg_name, script_name)   file "c:\python34\lib\runpy.py", line 85, in _run_code exec(code, run_globals)   file "c:/users/jaysp_000/firstsite/projectone\manage.py", line 10, in <module> execute_from_command_line(sys.argv)    file "c:\python34\lib\site-packages\django\core\management\__init__.py", line 338, in execute_from_command_line utility.execute()    file "c:\python34\lib\site-packages\django\core\management\__init__.py", line 330, in execute self.fetch_command(subcommand).run_from_argv(self.argv)    file "c:\python34\lib\site-packages\django\core\management\base.py", line 390, in run_from_argv self.execute(*args, **cmd_options)    file "c:\python34\lib\site-packages\django\core\management\base.py", line 441, in execute output = self.handle(*args, **options)    file "c:/users/jaysp_000/firstsite/projectone\blog_static\management\commands\update_blog1.py", line 78, in handle resp = client.get(path)    file "c:\python34\lib\site-packages\django\test\client.py", line 500, in **extra)    file "c:\python34\lib\site-packages\django\test\client.py", line 303, in return self.generic('get', path, secure=secure, **r)    file "c:\python34\lib\site-packages\django\test\client.py", line 379, in generic return self.request(**r)   file "c:\python34\lib\site-packages\django\test\client.py", line 448, in request response = self.handler(environ)   file "c:\python34\lib\site-packages\django\test\client.py", line 122, in __call__ response = self.get_response(request)   file "c:\python34\lib\site-packages\django\core\handlers\base.py", line 218, in get_response response = self.handle_uncaught_exception(request, resolver, sys.exc_info())   file "c:\python34\lib\site-packages\django\core\handlers\base.py", line 261, in handle_uncaught_exception return debug.technical_500_response(request, *exc_info)  file "c:\python34\lib\site-packages\django\views\debug.py", line 97, in technical_500_response html = reporter.get_traceback_html()  file "c:\python34\lib\site-packages\django\views\debug.py", line 384, in get_traceback_html return t.render(c)  file "c:\python34\lib\site-packages\django\template\base.py", line 209, in render return self._render(context)  file "c:\python34\lib\site-packages\django\template\base.py", line 201, in _render return self.nodelist.render(context)  file "c:\python34\lib\site-packages\django\template\base.py", line 903, in render bit = self.render_node(node, context)  file "c:\python34\lib\site-packages\django\template\debug.py", line 79, in render_node return node.render(context)  file "c:\python34\lib\site-packages\django\template\debug.py", line 89, in render output = self.filter_expression.resolve(context)  file "c:\python34\lib\site-packages\django\template\base.py", line 674, in resolve new_obj = func(obj, *arg_vals)  file "c:\python34\lib\site-packages\django\template\defaultfilters.py", line 771, in date return formats.date_format(value, arg)  file "c:\python34\lib\site-packages\django\utils\formats.py", line 136, in date_format return dateformat.format(value, get_format(format or 'date_format', use_l10n=use_l10n))  file "c:\python34\lib\site-packages\django\utils\formats.py", line 110, in get_format module in get_format_modules(lang):   file "c:\python34\lib\site-packages\django\utils\formats.py", line 82, in get_format_modules modules = _format_modules_cache.setdefault(lang, list(iter_format_modules(lang, settings.format_module_path)))   file "c:\python34\lib\site-packages\django\utils\formats.py", line 51, in iter_format_modules if not check_for_language(lang):   file "c:\python34\lib\site-packages\django\utils\translation\__init__.py", line 181, in check_for_language return _trans.check_for_language(lang_code)   file "c:\python34\lib\functools.py", line 472, in wrapper result = user_function(*args, **kwds)   file "c:\python34\lib\site-packages\django\utils\translation\trans_real.py", line 409, in check_for_language if not language_code_re.search(lang_code): typeerror: expected string or buffer 

here's code update_blog1

from django.core.management.base import basecommand django.core.urlresolvers import reverse django.test.client import client  import sys, os optparse import make_option  p1config.settings import staticblog_post_directory, staticblog_compile_directory  class command(basecommand):     = "compile blog posts html markdown, , upload images s3 defaults processing new blog posts"      option_list = basecommand.option_list + (          make_option(             '--all',             action='store_true',             dest='all',             default=false,             help='get blog posts, regardless of date'         ),      make_option(         '--name',         action='store',         dest='post_name',         default=false,         help='get named blog post'         ),     )      def handle(self, *args, **options):         verbosity = int(options.get('verbosity'))          client = client()         outdir = staticblog_compile_directory         posts = []         previews = []           if options['all']:             if verbosity > 3:                 print ('compiling blog posts')             posts = self._get_all_posts()         elif options['post_name']:             posts = self._get_named_posts(options['post_name'])         else:             if verbosity > 3:                 print ('compiling new blog posts')             posts = self._get_all_posts(new = true)          if verbosity > 3:             print ('%d posts found' % len(posts))             print ('----------------------------')          post in posts:               if verbosity > 3:                 print ("compiling " + post['md_name'] + " " +     post['html_name'])             path = reverse('blog_static.views.archive') + post['path']             # path = '/preview/' + post['path']             resp = client.get(path)             if os.path.exists(outdir + post['path']) == false:                 try:                     open(outdir + post['path'], 'r') f:                         pass                 except ioerror e:                     os.mkdir(outdir + post['path'])              open(outdir + post['html_name'], 'wb') f:                     f.write(resp.content)           if len(posts) > 0 , verbosity > 3:             print ('----------------------------')          if verbosity > 3:             print ('updating listings...')             print ('----------------------------')         path = reverse('blog_static.views.archive')         resp = client.get(path)          open(staticblog_compile_directory + 'index.html', 'wb') f:             f.write(resp.content)           if verbosity > 3:                 print ('done')       def _get_all_posts(self, new = false):             posts = []         item in os.listdir(staticblog_post_directory):             post = self._create_post(item, new)             if post:                 posts.append(post)         return posts      def _get_named_posts(self, post):         post_list = post.split(',')         posts = []         item in post_list:             try:                 open(staticblog_post_directory + item, 'r') f:                      post = self._create_post(item)                     if post:                         posts.append(post)             except ioerror e:                 print ('\033[01;31m' + str(e) + '\033[0m', file= sys.stderr)        return posts      def _create_post(self, item, new = false):         outdir = staticblog_post_directory         compiled_post = {             'md_name' : item,             'html_name' : '',             'path' : '',             'html' : '',         }         if item.endswith('.md'):             compiled_post['path'] = item.replace('.md', '')             compiled_post['html_name'] = compiled_post['path'] + '/index.html'             if new:                try:                     open(staticblog_compile_directory + compiled_post['html_name'], 'r') f:                      return false                 except ioerror e:                     return compiled_post             else:                 return compiled_post    

if in code, methods _get_named_posts(), _create_post(), handle() each have open() function embedded. these open() functions (ex: open(outdir + post['path'], 'r' or open(staticblog_post_directory + item, 'r')) problem lies, pointed out pycharm.

in view.py file, got have this...

# django imports django.template import requestcontext django.shortcuts import render_to_response, render django.core.files.storage import get_storage_class django.core.files.base import contentfile django.views.decorators.csrf import csrf_exempt django.db import models  # create 'shortcut' function wrap request in requestcontext() def render_response(req, *args, **kwargs):     """shortcut wrap request in requestcontext"""     kwargs['context_instance'] = requestcontext(req)     return render_to_response(*args, **kwargs)  # standard python lib import os, sys, urllib, hashlib  # 3rd party apps import markdown markdown.inlinepatterns import imagepattern, image_link_re  # config folder p1config.settings import staticblog_compile_directory, \                                 staticblog_post_directory, \                                 staticblog_storage  ###################################################################################  class s3imagepattern(imagepattern):     """ wrapper class handle image matches in markdown document """      def handlematch(self, match):         node = imagepattern.handlematch(self, match)         # check 'src' ensure local         src = node.attrib.get('src')         storage_class = get_storage_class(staticblog_storage)         storage = storage_class()          # otherwise need downloading!         if 'http://' in src or 'https://' in src:             img_data = urllib.request.urlopen(src).read()             md5 = hashlib.md5()             md5.update(img_data)             name = md5.hexdigest() + '/' + os.path.basename(src)         else:             open(staticblog_post_directory + src) fhandle:                 img_data = fhandle.read()             name = src          print('uploading ' + src, file=sys.stderr)         try:             storage.save(name, contentfile(img_data))             node.attrib['src'] = storage.url(name)             print ('uploaded ' + src + ' ' + storage.url(name), file=sys.stderr)         except exception e:             print(str(e), file=sys.stderr)             print ('\033[01;31mupload of %s failed\033[0m' % src, file=sys.stderr)         return node   def render_post(request, post_name):     """ render blog post based on .post template     used template rendered html in folder defined     staticblog_compile_directory     """     content = ""     mdown = markdown.markdown(extensions = ['meta',])     mdown.inlinepatterns['image_link'] = s3imagepattern(image_link_re, mdown)     try:         post_file_dir = os.path.join(staticblog_post_directory, post_name + '.md')             open(post_file_dir, 'r') pfdir:             content = pfdir.read()         # opening , reading entire '.md' document             html = mdown.convert(content)  # converting file '.md' ".html"      except ioerror e:         print (str(e))         open(os.path.join(staticblog_post_directory, 'preview2.md')) f:             content = f.read()             html = mdown.convert(content)      post = { 'content' : html, }      try:         post['date'] = mdown.meta['date'][0]         post['title'] = mdown.meta['title'][0]         post['author'] = mdown.meta['author'][0]         post['summary'] = mdown.meta['summary'][0]         post['tags'] = mdown.meta['tags'][0]     except:         pass      meta = {}     if 'title' in post:         meta['title'] = post['title']      # context object containing post, meta contexes     context = {'post' : post, 'meta' : meta}      return render_response(  # use render?         request,         'post2.html',         context     )   def archive(request):     mdown = markdown.markdown(extensions = ['meta',])     # create empty post list     posts = []     import string     # @ every 'item' in staticblog_compile_directory     item in os.listdir(staticblog_compile_directory):         # if 'item' in directory ends '.post' (like '.md' in markdown file, or '.py' in python file)         # more specifically, if there '.post' file located in directory...         if item.endswith('.md'):             # ...continue on and...             continue         # ...attempt use 'item'         try:             # ...by opening it,              open(os.path.join(staticblog_post_directory, item + '.md')) fhandle:                 # ...reading markdown file,                 content = fhandle.read() # (opening , reading entire '.md' document)                 # ...and converting html.                 mdown.convert(content)   # (converting file '.md' ".html")                  post = { 'name' : item, }                 if 'title' in mdown.meta , len(mdown.meta['title'][0]) > 0:                     # add markdown document's 'title' post[]                     # stores post's title "meta" section of '.md' document                     post['title'] = mdown.meta['title'][0]                 # if doesnt work...                 else:                     # add post list item's meta 'title', takes \n                     #   title of .md document , removes '-' it, \n                      #   can make post's title.                     post['title'] = string.capwords(item.replace('-', ' '))                 # ...and if there exists 'date' in item's meta attribute...                 if 'date' in mdown.meta:                     # pass 'date' info found in meta attribute 'date' \n                     #   variable created in post list                     post['date'] = mdown.meta['date'][0]                  posts.append(post)         except:             pass      operator import itemgetter     posts = sorted(posts, key=itemgetter('date'))     posts.reverse()      return render_response(  # use render?         request,         'archive.html',         {'posts' : posts}     )      @csrf_exempt def handle_hook(request):     django.http import httpresponse     django.core.management import call_command     result = call_command('update_blog', verbosity = 0)     return httpresponse(result) 

i dont know how fix this. can let me know how fix these issues? don't know can put string or buffer in code.


Comments

Popular posts from this blog

python - Healpy: From Data to Healpix map -

c - Bitwise operation with (signed) enum value -

xslt - Unnest parent nodes by child node -