0

I am developing with Flask, and am trying to create a page to create pages (as a sort of custom CMS). So the page will need to create its own @app.route decorator for a function that renders the page template when called in the app.py file. What I have come up with is to create three functions: remove_last_two_lines and create_rendering_func and add_back_last_lines (named for what they do). The remove_last_two_lines function and the add_back_last_lines function do exactly what I want. What I'm having trouble with is the create_rendering_func. It simply doesn't do anything, and doesn't raise an error. So I think the code is valid (and I am passing valid arguments), I just don't understand why it isn't working. The lines being overwritten are empty (that's why there is multiple newlines after the last line of the function). Thanks in advance!

def add_new_url(route, func_name, title, filename):
    lines = open(__file__, 'r').readlines()
    lines[-6] = '@app.route(\'%s\')' % route
    lines[-5] = '\ndef %s' % func_name
    lines[-4] = '\n\trender_template(\'filename\', the_title=%s)\n\n\n\n\n' % title 

(This method sucks. Any tips on better methods appreciated)

RyJo
  • 13
  • 2

1 Answers1

1

I would write the data to be inserted as a list of strings appended by newline characters (\n) and insert it into lines by slicing;

insert_lines = ["Hello\n", "World!\n"]
with open("my_text_file.txt") as myfile:
    lines = myfile.readlines()
    lines[-2:-2] = insert_lines
    myfile.seek(0)
    myfile.write(''.join(lines))

It necessitates reading the entire file into memory and creating a new file in memory before writing it, which could be a problem if your file is incredibly big, but it will insert "Hello" and "World!" before the second to last line of the file.

JacaByte
  • 325
  • 2
  • 8