How can I save a document from web page on server side? - python

I'm using apache and python to run my web pages. But when I try to save even a txt file generated on the fly, the file is not saved.
def save(req):
try:
fe1=req.form['fe1']
fe2=req.form['fe2']
file=open("file.txt",'w')
file.write("%s %s" %(fe1,fe2))
file.close()
except KeyError:
fe1=''
fe2=''
view="""
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<form method=post action="#">
<input type='text' id='fe1'></input>
<input type='text' id='fe2'></input>
<input type='submit'>
</form>
</body>
</html>
""".format(**locals())
return (view)
After I submi the form I get this:
Mod_python error: "PythonHandler mod_python.publisher"
Traceback (most recent call last):
File "/usr/lib64/python2.7/site-packages/mod_python/apache.py", line 399, in HandlerDispatch
result = obj(req)
File "/usr/lib64/python2.7/site-packages/mod_python/publisher.py", line 222, in handler
published = publish_object(req, object)
File "/usr/lib64/python2.7/site-packages/mod_python/publisher.py", line 446, in publish_object
return publish_object(req, util.apply_fs_data(obj, req.form, req=req))
File "/usr/lib64/python2.7/site-packages/mod_python/util.py", line 642, in apply_fs_data
return object(**args)
File "<string>", line 5, in save
IOError: [Errno 13] Permission denied: 'file.txt'

Related

WTForms Field shows up when run, but has Unbound problems

I'm new to Flask and JS, so I'm really not sure what the problem is here.
app.py
#app.route('/email', methods=["GET", "POST"])
def email():
email_form = EmailForm(csrf_enabled=False)
return render_template("email-form.html", template_form=email_form, action='/appliance2', method='POST')
forms.py (I created that validator using the template from the wtForms docs)
class DBPresenceCheck(object):
def __init__(self, table, message="Field is invalid"):
self.table = table
self.message = message
def __call__(self, form, field):
presence = Connector().query('SELECT 1 FROM %(table)s WHERE %(col_name)s = %(data)s LIMIT 1;',
{'col_name': field.label, 'data': field.data, 'table': self.table})
if presence == 1:
raise ValidationError(self.message)
class EmailForm(FlaskForm):
title = "Enter Household Info"
subtitle = "Please enter your email address:"
email_input = StringField("email", validators=[email(),
DBPresenceCheck('Household', 'That email is already present in the database.')])
# print(email_input.data)
submit = SubmitField("Submit")
email-form.html
{% extends "base.html" %}
{% block content%}
<div class="container py-4">
<div class="p-5 mb-4 bg-light rounded-3">
<h2 class="display-5 fw-bold">{{ template_form.title }}</h2>
<p class="col-md-8 fs-4">{{ template_form.subtitle }}</p>
<form action="{{ action }}" method="{{ method }}">
<div id="main_elements">
{{ template_form['email_input']() }}
</div>
<div id="submit_element">
<br>
{{ template_form["submit"](class_="btn btn-primary") }}
</div>
</form>
</div>
</div>
{%endblock%}
I first realized something was wrong when I was testing the validation, and neither validator ever threw. I added the print statement in forms, and now, when I use flask run, I get the following error.
Traceback (most recent call last):
File "C:\Languages\Python\3.9\lib\runpy.py", line 197, in _run_module_as_main
return _run_code(code, main_globals, None,
File "C:\Languages\Python\3.9\lib\runpy.py", line 87, in _run_code
exec(code, run_globals)
File "C:\Users\askat\.virtualenvs\askat-YHGTcgZo\Scripts\flask.exe\__main__.py", line 7, in <module>
File "C:\Users\askat\.virtualenvs\askat-YHGTcgZo\lib\site-packages\flask\cli.py", line 1047, in main
cli.main()
File "C:\Users\askat\.virtualenvs\askat-YHGTcgZo\lib\site-packages\click\core.py", line 1055, in main
rv = self.invoke(ctx)
File "C:\Users\askat\.virtualenvs\askat-YHGTcgZo\lib\site-packages\click\core.py", line 1657, in invoke
return _process_result(sub_ctx.command.invoke(sub_ctx))
File "C:\Users\askat\.virtualenvs\askat-YHGTcgZo\lib\site-packages\click\core.py", line 1404, in invoke
return ctx.invoke(self.callback, **ctx.params)
File "C:\Users\askat\.virtualenvs\askat-YHGTcgZo\lib\site-packages\click\core.py", line 760, in invoke
return __callback(*args, **kwargs)
File "C:\Users\askat\.virtualenvs\askat-YHGTcgZo\lib\site-packages\click\decorators.py", line 84, in new_func
return ctx.invoke(f, obj, *args, **kwargs)
File "C:\Users\askat\.virtualenvs\askat-YHGTcgZo\lib\site-packages\click\core.py", line 760, in invoke
return __callback(*args, **kwargs)
File "C:\Users\askat\.virtualenvs\askat-YHGTcgZo\lib\site-packages\flask\cli.py", line 911, in run_command
raise e from None
File "C:\Users\askat\.virtualenvs\askat-YHGTcgZo\lib\site-packages\flask\cli.py", line 897, in run_command
app = info.load_app()
File "C:\Users\askat\.virtualenvs\askat-YHGTcgZo\lib\site-packages\flask\cli.py", line 312, in load_app
app = locate_app(import_name, None, raise_if_not_found=False)
File "C:\Users\askat\.virtualenvs\askat-YHGTcgZo\lib\site-packages\flask\cli.py", line 218, in locate_app
__import__(module_name)
File "C:\Users\askat\PycharmProjects\cs6400-2022-03-Team060\Phase_3\app.py", line 4, in <module>
from forms import *
File "C:\Users\askat\PycharmProjects\cs6400-2022-03-Team060\Phase_3\forms.py", line 33, in <module>
class EmailForm(AddForm):
File "C:\Users\askat\PycharmProjects\cs6400-2022-03-Team060\Phase_3\forms.py", line 37, in EmailForm
print(email_input.data)
AttributeError: 'UnboundField' object has no attribute 'data'
If the print statement is just print(email_input), then when I run it, the following output
<UnboundField(StringField, ('email',), {'validators': [<wtforms.validators.Email object at 0x0000024145A4F460>, <forms.DBPresenceCheck object at 0x0000024145A4F610>]})>
but no errors are thrown. It seems strange to me that the error is thrown before the field is even created.
In the validators list you need to pass in an instance of class Email. So you field should read:
from wtforms.validators import Email
email_input = StringField("email", validators=[Email(), ...
and don't forget to install the email package as Flask-WTF doesn't include anymore the Email in their validators.

'list' object has no attribute 'startswith' with Django and scrapy integration

I am getting this peculiar error after I try to runserver once I have finished web-crawling as my web-crawler is connected to django :
Exception in thread django-main-thread:
Traceback (most recent call last):
File "/Users/usr/opt/anaconda3/lib/python3.8/threading.py", line 932, in _bootstrap_inner
self.run()
File "/Users/usr/opt/anaconda3/lib/python3.8/threading.py", line 870, in run
self._target(*self._args, **self._kwargs)
File "/Users/usr/cruises/venv/lib/python3.8/site-packages/django/utils/autoreload.py", line 64, in wrapper
fn(*args, **kwargs)
File "/Users/usr/cruises/venv/lib/python3.8/site-packages/django/core/management/commands/runserver.py", line 134, in inner_run
self.check(display_num_errors=True)
File "/Users/usr/cruises/venv/lib/python3.8/site-packages/django/core/management/base.py", line 487, in check
all_issues = checks.run_checks(
File "/Users/usr/cruises/venv/lib/python3.8/site-packages/django/core/checks/registry.py", line 88, in run_checks
new_errors = check(app_configs=app_configs, databases=databases)
File "/Users/usr/cruises/venv/lib/python3.8/site-packages/django/core/checks/urls.py", line 107, in check_url_settings
value = getattr(settings, name)
File "/Users/usr/cruises/venv/lib/python3.8/site-packages/django/conf/__init__.py", line 93, in __getattr__
val = self._add_script_prefix(val)
File "/Users/usr/cruises/venv/lib/python3.8/site-packages/django/conf/__init__.py", line 140, in _add_script_prefix
if value.startswith(("http://", "https://", "/")):
AttributeError: 'list' object has no attribute 'startswith'
It seems to be an error located in one of the django files rather than from my script. However, I am strongly convinced something in my script is causing this.
Here's my script:
from django.db import models
class Cruises(models.Model):
title = models.CharField(max_length=200)
views.py:
from django.shortcuts import render
from .models import Cruises
def basic(request):
long_list = Cruises.objects.values('title')
return render(request, 'cruise_control/basic.html', context = {'long_list':long_list})
urls.py
from django.urls import path
from . import views
urlpatterns = [
path('',views.basic, name = 'basic')
]
basic.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Cruises</title>
</head>
<body>
<h1> Cruise Control </h1>
{% for lng_l in long_list %}
<form action="/action_page.php">
<label for='destination'>Destination</label>
<input type="text" list="destination" />
<datalist id="destination">
<option>{{lng_l.title}}</option>
</datalist>
<!label for="cruisetime">Departure date</label>
<!input type="date" id="cruisetime" name="cruisetime" min={{dep_l.departureDate}}>
<!input type="submit">
</form>
{% endfor %}
</body>
</html>
I did the following to remove the databases:
find . -path "*/migrations/*.py" -not -name "__init__.py" -delete
find . -path "*/migrations/*.pyc" -delete
rm db.sqlite3
However, the error still occurs.
Turns out the error occurs from this line in my settings:
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
However, this is suppose to create a media folder for me to store images into via
from django.contrib import admin
from django.urls import path, include
from django.conf.urls.static import static
from django.conf import settings
urlpatterns = [
path('', include('cruise_control.urls')),
path(r'^admin/', admin.site.urls),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
I cannot understand why this is throwing an error because it's working on another scrapy+django setup that I have.
Turns out that I needed the following:
MEDIA_URL = '/media/'
Instead, I had
MEDIA_URL = []

Loading audio file to template causes ConnectionResetError: [Errno 54] Connection reset by peer (Django, Python)

I am making an audio player webapp using Django. The audio files are uploaded by admin via a model that adds the file to my Media directory. Then in my template the audio files are displayed with an individual audio player.
{% for song in songs %}
<audio class="player" controls>
<source src="{{ song.audio_file.url }}" type="audio/wav">
</audio>
{% endfor %}
Now, the website works as intended. The audio players all become visible and are working correctly. However in my terminal, every time the page is loaded I get errors of this type (depending on how many audio files that are to be displayed, if there only is one file i get this for example):
[13/Dec/2019 12:03:31] "GET /media/ap/song.wav HTTP/1.1" 200 1626112
----------------------------------------
Exception happened during processing of request from ('127.0.0.1', 60242)
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/socketserver.py", line 639, in process_request_thread
self.finish_request(request, client_address)
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/socketserver.py", line 361, in finish_request
self.RequestHandlerClass(request, client_address, self)
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/socketserver.py", line 696, in __init__
self.handle()
File "/Users/oscarjonsson/python-virtual-environments/django_env/lib/python3.6/site-packages/django/core/servers/basehttp.py", line 174, in handle
self.handle_one_request()
File "/Users/oscarjonsson/python-virtual-environments/django_env/lib/python3.6/site-packages/django/core/servers/basehttp.py", line 182, in handle_one_request
self.raw_requestline = self.rfile.readline(65537)
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/socket.py", line 586, in readinto
return self._sock.recv_into(b)
ConnectionResetError: [Errno 54] Connection reset by peer
What could be the cause of this? Would appreciate any help.
You can use this code that might be helpful:
{% for song in songs %}
<audio class="player" controls>
<source src="{% if song.audio_file %}{{ song.audio_file.url }} {% endif %}" type="audio/wav">
</audio>
{% endfor %}

Image upload error using Bottle

In my code .tpl file:
<form method='post' action='/upload' enctype='multipart/form-data'>
<input type='file' name='newfile'>
<input type='submit' value='Submit'>
</form>
My controller code is:
#app.post('/upload')
def upload():
newfile = request.files.get('newfile')
save_path = os.path.join(config.UPLOAD_DIRECTORY, newfile.filename)
newfile.save(save_path)
return redirect('/')
After browse and submit, I got following 500 error.
Internal Server Error
Exception: AttributeError('save',)
Traceback:
Traceback (most recent call last):
File "/var/www/myproject/bottle.py", line 768, in _handle
return route.call(**args)
File "/var/www/myproject/bottle.py", line 1518, in wrapper
rv = callback(*a, **ka)
File "/var/www/myproject/controllers/index.py", line 753, in upload
newfile.save(save_path)
File "/usr/lib/python2.7/cgi.py", line 521, in __getattr__
raise AttributeError, name
AttributeError: save
Could someone know what this issue is?
Oh I see a problem...
return redirect('/')
Should be:
redirect('/')
That could what is generating your 500 issue.

multiple routes and function in bottle framework

I'm trying to modify already existing code, simply add form to add photos.
python:
#route('/photos/add')
#jinja_view('add.html')
#post('/photos/add')
def upload_func():
upload = request.files.get('pic')
name, ext = os.path.splitext(upload.filename)
if ext not in ('.png', '.jpg', '.jpeg'):
return "ext is not allowed"
save_path = "/src/photo_gallery/photos"
upload.save(save_path)
return "photo is saved"
HTML:
<form action="/photos/add" method="post">
<div align="center">
<label>Picture</label>
<input type="file" name="pic" required>
</div>
<div>
<label>Info</label>
<input type="text" name="text">
</div>
<div>
<input type="submit" value="add">
</div>
</form>
server log:
Traceback (most recent call last):
File "/home/empty/python/bottle/lib/python3.5/site-packages/bottle.py", line 862, in _handle
return route.call(**args)
File "/home/empty/python/bottle/lib/python3.5/site-packages/bottle.py", line 1740, in wrapper
rv = callback(*a, **ka)
File "/home/empty/python/bottle/lib/python3.5/site-packages/bottle.py", line 3635, in wrapper
result = func(*args, **kwargs)
File "/home/empty/python/bottle/src/photo_gallery/app.py", line 50, in upload_func
name, ext = os.path.splitext(upload.filename)
AttributeError: 'NoneType' object has no attribute 'filename'
127.0.0.1 - - [22/Dec/2016 23:20:42] "GET /photos/add HTTP/1.1" 500 751
You have linked the url path /photos/add to the callback function upload_func. It looks like you want to support two request types (GET and POST), then function decorators should look like this:
#route('/photos/add', method=['GET', 'POST'])
#jinja_view('add.html')
def upload_func():
# ...
Take a look at:
https://bottlepy.org/docs/dev/tutorial.html#request-routing
https://bottlepy.org/docs/dev/api.html#bottle.Bottle.route
Please also note that the code should not be written like this - too complex

Categories