'Rename title in storage without creating new one in bootle python
I'm new to this. My problem is when I want to edit the text in aritcle(Artikel) everything seems fine, but when I edit the name/title it's creating a new article with the edited version, while the first article title I tried to change exists.
I think is "fname = "storage/" + name" which ruining everything
@route("/new-page", method="POST")
def new_page():
name = getattr(request.forms, "title")
text = getattr(request.forms, "text")
**fname = "storage/" + name**
with open(fname, "w") as mfile:
mfile.write(name + text)
mfile.close()
redirect("/")
import json
from bottle import run, route, template, static_file, request, redirect
from os import listdir
def file_scan(fname):
fname = "storage/" + fname
try:
mfile = open(fname, "r")
pages = mfile.read()
mfile.close()
return pages
except:
mfile = open(fname, "w")
mfile.write([])
mfile.close()
return []
def file_print():
file = listdir("storage")
files = []
for i in file:
if i != ".DS_Store":
i.split()
files.append(i)
return files
@route('/')
def index():
return template("index", files=file_print())
@route("/add")
def edit_form():
return template("add", files=file_print())
@route("/edit/<name>")
def edit(name):
return template("edit", files=file_print(), name=name, text=file_scan(name))
@route("/wiki/<name>")
def wiki(name):
return template("wiki", text=file_scan(name), name=name, files=file_print())
@route("/new-page", method="POST")
def new_page():
name = getattr(request.forms, "title")
text = getattr(request.forms, "text")
fname = "storage/" + name
with open(fname, "w") as mfile:
mfile.write(name + text)
mfile.close()
redirect("/")
run(host="127.0.0.1", port=8000)```
Solution 1:[1]
First you can call request.forms.get('title')
2 ways to solve this problem.
Create an ID that stays with the document, which will require you to track the relationship of the ID and Title in a database
If they change the title, have a hidden input that is a copy of the original and rename the file to the new name. This keeps you from keeping track of an ID in a database, but can get messy.
Example:
@route("/new-page", method="POST")
def new_page():
name = request.forms.get("title")
orig = request.forms.get("original")
text = request.forms.get("text")
if orig and orig in os.path.exists(f'storage/{orig}':
os.rename(f'storage/{orig}', f'storage/{name}')
fname = "storage/" + name
with open(fname, "w") as mfile:
mfile.write(name + text)
mfile.close()
redirect("/")
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | eatmeimadanish |
