Forums

OSError: [Errno 2] No such file or directory

I have the below code to make a directory and then have a file upload to the directory. The same code works fine in a similar view in the same app, so I'm not sure what to think. Any ideas?

> > 2015-02-27 06:18:43,275 :/usr/lib/python2.7/threading.py:1160: RuntimeWarning: tp_compare didn't return -1 or -2 for exception
> 2015-02-27 06:18:43,276 :  return _active[_get_ident()] 2015-02-27
> 06:18:43,276 :Traceback (most recent call last): 2015-02-27
> 06:18:43,276 :  File "/bin/user_wsgi_wrapper.py", line 130, in
> __call__ 2015-02-27 06:18:43,276 :    self.error_log_file.logger.exception("Error running WSGI application")
> 2015-02-27 06:18:43,276 :  File
> "/usr/lib/python2.7/logging/__init__.py", line 1185, in exception
> 2015-02-27 06:18:43,276 :    self.error(msg, *args, **kwargs)
> 2015-02-27 06:18:43,277 :  File
> "/usr/lib/python2.7/logging/__init__.py", line 1178, in error
> 2015-02-27 06:18:43,277 :    self._log(ERROR, msg, args, **kwargs)
> 2015-02-27 06:18:43,277 :  File
> "/usr/lib/python2.7/logging/__init__.py", line 1270, in _log
> 2015-02-27 06:18:43,277 :    record = self.makeRecord(self.name,
> level, fn, lno, msg, args, exc_info, func, extra) 2015-02-27
> 06:18:43,277 :  File "/usr/lib/python2.7/logging/__init__.py", line
> 1244, in makeRecord 2015-02-27 06:18:43,277 :    rv = LogRecord(name,
> level, fn, lno, msg, args, exc_info, func) 2015-02-27 06:18:43,278 : 
> File "/usr/lib/python2.7/logging/__init__.py", line 284, in __init__
> 2015-02-27 06:18:43,278 :    self.threadName =
> threading.current_thread().name 2015-02-27 06:18:43,278 :  File
> "/usr/lib/python2.7/threading.py", line 1160, in currentThread
> 2015-02-27 06:18:43,278 :    return _active[_get_ident()] 2015-02-27
> 06:18:43,278 :  File "/bin/user_wsgi_wrapper.py", line 122, in
> __call__ 2015-02-27 06:18:43,278 :    app_iterator = self.app(environ, start_response) 2015-02-27 06:18:43,278 :  File
> "/home/leapfrog/.local/lib/python2.7/site-packages/flask/app.py", line
> 1836, in __call__ 2015-02-27 06:18:43,288 :    return
> self.wsgi_app(environ, start_response) 2015-02-27 06:18:43,288 :  File
> "/home/leapfrog/.local/lib/python2.7/site-packages/flask/app.py", line
> 1820, in wsgi_app 2015-02-27 06:18:43,292 :    response =
> self.make_response(self.handle_exception(e)) 2015-02-27 06:18:43,292 :
> File "/home/leapfrog/.local/lib/python2.7/site-packages/flask/app.py",
> line 1403, in handle_exception 2015-02-27 06:18:43,292 :   
> reraise(exc_type, exc_value, tb) 2015-02-27 06:18:43,293 :  File
> "/home/leapfrog/.local/lib/python2.7/site-packages/flask/app.py", line
> 1817, in wsgi_app 2015-02-27 06:18:43,293 :    response =
> self.full_dispatch_request() 2015-02-27 06:18:43,293 :  File
> "/home/leapfrog/.local/lib/python2.7/site-packages/flask/app.py", line
> 1477, in full_dispatch_request 2015-02-27 06:18:43,294 :    rv =
> self.handle_user_exception(e) 2015-02-27 06:18:43,294 :  File
> "/home/leapfrog/.local/lib/python2.7/site-packages/flask/app.py", line
> 1381, in handle_user_exception 2015-02-27 06:18:43,295 :   
> reraise(exc_type, exc_value, tb) 2015-02-27 06:18:43,295 :  File
> "/home/leapfrog/.local/lib/python2.7/site-packages/flask/app.py", line
> 1475, in full_dispatch_request 2015-02-27 06:18:43,296 :    rv =
> self.dispatch_request() 2015-02-27 06:18:43,296 :  File
> "/home/leapfrog/.local/lib/python2.7/site-packages/flask/app.py", line
> 1461, in dispatch_request 2015-02-27 06:18:43,297 :    return
> self.view_functions[rule.endpoint](**req.view_args) 2015-02-27
> 06:18:43,297 :  File
> "/home/leapfrog/.local/lib/python2.7/site-packages/flask_login.py",
> line 758, in decorated_view 2015-02-27 06:18:43,298 :    return
> func(*args, **kwargs) 2015-02-27 06:18:43,298 :  File
> "/home/leapfrog/ci3/app.py", line 399, in upload_school_profile
> 2015-02-27 06:18:43,299 :    os.mkdir('static/schools/' + dir_name)
> 2015-02-27 06:18:43,299 :OSError: [Errno 2] No such file or directory:
> 'static/schools/acme_school/'

The code from the views is below:

@app.route('/upload/schoolprofile/<int:id>', methods=['GET', 'POST'])
@login_required
def upload_school_profile(id):
    form = AddSchoolDoc()
    school = School.query.filter_by(id=id).first()
    documents = SchoolDoc.query.filter_by(school_id=id)
    if form.validate_on_submit():
        # for document in form:
        dir_name = str(school.id) + '_' + school.englishname.replace(' ','_').lower() + '/'
        try:
            os.stat('static/schools/' + dir_name)
        except:
            os.mkdir('static/schools/' + dir_name)
        pic_files = request.files.getlist("picfiles[]")
        doc_files = request.files.getlist("docfiles[]")
        if pic_files[0].filename:
            for item in pic_files:
                if allowed_file(item.filename.lower()):
                    item.save('static/schools' + dir_name + secure_filename(item.filename.lower()))
                    picdata = SchoolDoc(type='picture', filename=secure_filename(item.filename.lower()),
                        path=dir_name, school_id=id, contenttype=item.content_type)
                    db.session.add(picdata)
                    db.session.commit()
                else:
                    flash('Picture type not supported', 'danger')
            flash('Pictures uploaded successfully', 'success')
            return render_template("addschooldoc.html", form=form, school=school, documents=documents)
        if doc_files[0].filename:
            for item in doc_files:
                if allowed_file(item.filename.lower()):
                    item.save('static/schools' + dir_name + secure_filename(item.filename.lower()))
                    docdata = SchoolDoc(type='document', filename=secure_filename(item.filename.lower()),
                        path=dir_name, school_id=id, contenttype=item.content_type)
                    db.session.add(docdata)
                    db.session.commit()
                else:
                    flash('Document type not supported', 'danger')
            flash('Documents uploaded successfully', 'success')
            return render_template("addschooldoc.html", form=form, school=school, documents=documents)
        flash('Form submitted successfully', 'success')
        return render_template("addschooldoc.html", form=form, school=school, documents=documents)
    return render_template("addschooldoc.html", form=form, school=school, documents=documents)

I launched a console from the base directory and used os.mkdir('static/schools/acme_school') to successfully create a new directoy. What gives?

Try os.mkdir('/static/schools/acme_school')

If you look at the error,

No such file or directory:
> 'static/schools/acme_school/'

you will see that it means that it cannot find static/schools, or even static, and that's why it cannot mkdir acme_school there.

So you should use an absolute file path instead of a relative path because you never know where the current working directory is. That is what graingerkid is saying with the extra '/' in front. However, the correct file path is probably something like /home/leapfrog/<your-webapp-name>/static/schools/acme_school/

Also as a side note, I just want to point out that you want to serve your static files staticly, otherwise your website will be super slow later on.

@graingerkid @conrad Your responses are much appreciated and thanks for the info on serving the files staticly. I changed the path to an absolute path as conrad suggested and it now works fine now.