Exemplo n.º 1
0
	def get(self):
		template_values = {
			'pagename': 'about',
			'categories': get_all_categories(),
			'tags': get_all_tags(),
			'unsorted_count': count_unsorted(),
		}
		path = os.path.join(os.path.dirname(__file__), 'pages/about.html')
		self.response.out.write(template.render(path, template_values))
Exemplo n.º 2
0
	def get(self):
		archives = Archive.all().order('-year').order('-month').fetch(1000)

		template_values = {
			'pagename': 'archive',
			'archives': archives,
			'tags': get_all_tags(),
			'categories': get_all_categories(),
			'unsorted_count': count_unsorted(),
		}

		path = os.path.join(os.path.dirname(__file__), 'pages/archive.html')
		self.response.out.write(template.render(path, template_values))
Exemplo n.º 3
0
	def get(self):
		temp = self.request.path.split('/')
		permalink = temp[2]

		article = db.GqlQuery('''select * from Article where
							  	 permalink = :1''', permalink).get()

		# No article is found, redirect to 404
		if article == None:
			path = os.path.join(os.path.dirname(__file__), 'pages/error.html')
			self.response.out.write(template.render(path, None))
			return

		chtml = captcha.displayhtml(
				    public_key = '6LfrwroSAAAAAOeG4fkb6pA9enyK1FIdv3g0J2yH',
					use_ssl = False,
					error = None)

		template_values = {
			'article': article,
			'article_tags': article.tags(),
			'pagename': 'readArticle',
			'messages': article.comments,

			'save_nickname': self.save_nickname,
			'save_email': self.save_email,
			'save_website': self.save_website,
			'save_msg': self.save_msg,
			'save_ref': self.save_ref,
			'save_refname': self.save_refname,
			'save_showcancel': self.save_showcancel,
			'save_msgid': self.save_msgid,

			'captcha_error': self.captcha_error,
			'captchahtml': chtml,

			'categories': get_all_categories(),
			'tags': get_all_tags(),
			'unsorted_count': count_unsorted(),
		}

		path = os.path.join(os.path.dirname(__file__), 'pages/readArticle.html')
		self.response.headers['Content-Type'] = 'text/html;charset=utf-8'
		self.response.out.write(template.render(path, template_values))
    def process_POST(self, request):
        """
        Function that will be called upon receiving a POST request for the
        aforementioned URL.
        """
        # Parse the given parameters.
        event_id = request.args0.get("event", None)
        is_synthetic = request.args0.get("synthetic", None)
        tag = request.args0.get("tag", "")
        if isinstance(is_synthetic, basestring) and \
                is_synthetic.lower() in lowercase_true_strings:
            is_synthetic = True
        else:
            is_synthetic = False

        # Every waveform MUST be bound to an event.
        if event_id is None:
            msg = ("No event parameter passed. Every waveform "
                "must be bound to an existing event.")
            raise InvalidParameterError(msg)

        if not event_exists(event_id, self.env):
            msg = "The given event resource name '%s' " % event_id
            msg += "is not known to SeisHub."
            raise InvalidParameterError(msg)

        # There are two possibilities for getting data inside the database:
        # upload the file directly to SeisHub or just give a file URL that the
        # server can find.
        filename = request.args0.get("index_file", None)
        # If the 'index_file' parameter is not given, assume the file will be
        # directly uploaded.
        if filename is None:
            waveform_data = request.content
            waveform_data.seek(0, 0)
            file_is_managed_by_seishub = True
        else:
            filename = os.path.abspath(filename)
            if not os.path.exists(filename) or \
                    not os.path.isfile(filename):
                msg = "File '%s' cannot be found by the SeisHub server." % \
                    filename
                raise InvalidParameterError(msg)
            with open(filename, "rb") as open_file:
                waveform_data = StringIO(open_file.read())
            waveform_data.seek(0, 0)
            file_is_managed_by_seishub = False

        # Check if file exists. Checksum is returned otherwise. Raises on
        # failure.
        data = waveform_data.read()
        waveform_data.seek(0, 0)
        md5_hash = check_if_file_exist_in_db(data, self.env)

        msg = ("The data does not appear to be a valid waveform file. Only "
               "data readable by ObsPy is acceptable.")
        # Only valid waveforms files will be stored in the database. Valid is
        # defined by being readable by ObsPy.
        try:
            st = read(waveform_data)
        except:
            raise InvalidObjectError(msg)

        # Replace network, station and channel codes with placeholders if they
        # do not exist. Location can be an empty string.
        network = st[0].stats.network if st[0].stats.network else "XX"
        station = st[0].stats.station if st[0].stats.station else "XX"
        location = st[0].stats.location
        channel = st[0].stats.channel if st[0].stats.channel else "XX"

        # Check if the tag is valid, e.g. that it fulfulls the constraints of
        # being unique per channel_id and event.
        tags = get_all_tags(network, station, location, channel, event_id,
            self.env)
        if tag in tags:
            msg = "Tag already exists for the given channel id and event."
            raise InvalidParameterError(msg)

        if file_is_managed_by_seishub is True:
            # Otherwise create the filename for the file, and check if it
            # exists.
            filename = os.path.join(self.env.config.get("event_based_data",
                "waveform_filepath"), event_id,
                ("{network}.{station}.{location}.{channel}-"
                "{year}_{month}_{day}_{hour}"))
            t = st[0].stats.starttime
            filename = filename.format(network=network, station=station,
                channel=channel, location=location, year=t.year, month=t.month,
                day=t.day, hour=t.hour)

            # Write the data to the filesystem. The final filename is returned.
            filename = write_string_to_filesystem(filename, data)

        # Use only one session to be able to take advantage of transactions.
        session = self.env.db.session(bind=self.env.db.engine)

        # Wrap in try/except and rollback changes in case something fails.
        try:
            # Add information about the uploaded file into the database.
            filepath = add_filepath_to_database(session, filename, len(data),
                    md5_hash, is_managed_by_seishub=file_is_managed_by_seishub)

            # Loop over all traces in the file.
            for trace in st:
                stats = trace.stats

                # Extract coordinates if it is a sac file. Else set them to
                # None.
                if hasattr(stats, "sac"):
                    # Invalid floating point value according to the sac
                    # definition.
                    iv = -12345.0
                    sac = stats.sac
                    latitude = sac.stla if sac.stla != iv else None
                    longitude = sac.stlo if sac.stlo != iv else None
                    elevation = sac.stel if sac.stel != iv else None
                    local_depth = sac.stdp if sac.stdp != iv else None
                else:
                    latitude, longitude, elevation, local_depth = [None] * 4

                # Add the channel if it does not already exists, or update the
                # location or just return the existing station. In any case a
                # channel column object will be returned.
                channel_row = add_or_update_channel(session,
                    stats.network, stats.station, stats.location,
                    stats.channel, latitude, longitude, elevation, local_depth)

                # Add the current waveform channel as well.
                waveform_channel = WaveformChannelObject(
                    channel=channel_row, filepath=filepath,
                    event_resource_id=event_id,
                    starttime=stats.starttime.datetime,
                    endtime=stats.endtime.datetime, tag=tag,
                    sampling_rate=stats.sampling_rate, format=stats._format,
                    is_synthetic=is_synthetic)
                session.add(waveform_channel)

                session.commit()
        except Exception, e:
            # Rollback session.
            session.rollback()
            session.close()

            # Remove the file if something failes..
            if file_is_managed_by_seishub:
                os.remove(filename)
            msg = e.message + " - Rolling back all changes."
            raise InternalServerError(msg)
Exemplo n.º 5
0
	def get(self):
#		arts = Article.all().order('-time_stamp').fetch(100)
#
#		arts[3].link_prev = ''
#		arts[3].year_prev = 0
#		arts[3].month_prev = 0
#		arts[3].day_prev = 0
#		arts[3].title_prev = ''
#		arts[3].link_next = arts[2].permalink
#		arts[3].year_next = arts[2].year
#		arts[3].month_next = arts[2].month
#		arts[3].day_next = arts[2].day
#		arts[3].title_next = arts[2].thetitle
#
#		arts[2].link_prev = arts[3].permalink
#		arts[2].year_prev = arts[3].year
#		arts[2].month_prev = arts[3].month
#		arts[2].day_prev = arts[3].day
#		arts[2].title_prev = arts[3].thetitle
#		arts[2].link_next = arts[1].permalink
#		arts[2].year_next = arts[1].year
#		arts[2].month_next = arts[1].month
#		arts[2].day_next = arts[1].day
#		arts[2].title_next = arts[1].thetitle
#
#		arts[1].link_prev = arts[2].permalink
#		arts[1].year_prev = arts[2].year
#		arts[1].month_prev = arts[2].month
#		arts[1].day_prev = arts[2].day
#		arts[1].title_prev = arts[2].thetitle
#		arts[1].link_next = arts[0].permalink
#		arts[1].year_next = arts[0].year
#		arts[1].month_next = arts[0].month
#		arts[1].day_next = arts[0].day
#		arts[1].title_next = arts[0].thetitle
#
#		arts[0].link_prev = arts[1].permalink
#		arts[0].year_prev = arts[1].year
#		arts[0].month_prev = arts[1].month
#		arts[0].day_prev = arts[1].day
#		arts[0].title_prev = arts[1].thetitle
#		arts[0].link_next = ''
#		arts[0].year_next = 0
#		arts[0].month_next = 0
#		arts[0].day_next = 0
#		arts[0].title_next = ''
#
#		for a in arts:
#			a.put()
#
#		self.redirect('http://www.baidu.com');


		try:
			pageno = int(self.request.path.split('/')[-1])
		except ValueError:
			pageno = 1

		query = Article.all().order('-time_stamp')
		group = query.fetch(1000)

		article_list = []
		pagei = 0
		start = 0
		length = len(group)

		while group != [] and article_list == []:
			while start + self.article_per_page - 1 < length:
				pagei = pagei + 1
				if pagei == pageno:
					article_list = group[start : start + self.article_per_page]
				start = start + self.article_per_page
			if len(group[start : start + self.article_per_page]) > 0:
				pagei = pagei + 1
				if pagei == pageno:
					article_list = group[start : start + self.article_per_page]

			last_time = group[-1].time_stamp
			query.filter('time_stamp <', last_time)
			group = query.fetch(1000)

		show_left_arrow = 1 if pageno > 1 else 0
		show_right_arrow = 1 if pageno < pagei else 0
		show_left_dot = 1 if pageno >= 5 else 0
		show_right_dot = 1 if pageno <= pagei - 4 else 0

		pageno_list = [i for i in range(max(1, pageno - 3), min(pagei + 1, pageno + 4))]

		template_values = {
			'articles': article_list,
			'pagename': 'articles',
			'page_current': pageno,
			'page_total': pagei,
			'pageno_list': pageno_list,
			'show_left_arrow': show_left_arrow,
			'show_right_arrow': show_right_arrow,
			'show_left_dot': show_left_dot,
			'show_right_dot': show_right_dot,
			'page_prev': max(1, pageno - 1),
			'page_next': min(pagei, pageno + 1),
			'categories': get_all_categories(),
			'tags': get_all_tags(),
			'unsorted_count': count_unsorted(),
		}

		path = os.path.join(os.path.dirname(__file__), 'pages/articles.html')
		self.response.headers['Content-Type'] = 'text/html;charset=utf-8'
		self.response.out.write(template.render(path, template_values))
Exemplo n.º 6
0
	def get(self):
		temp = self.request.path.split('/')
		key = temp[1]

		try:
			pageno = int(temp[-1])
		except ValueError:
			pageno = 1

		if key == 'category':
			if len(temp) == 4 or len(temp) > 3 and temp[3] != 'page':
				path = os.path.join(os.path.dirname(__file__), 'pages/error.html')
				self.response.out.write(template.render(path, None))
				return

			name = unicode(urllib.unquote(temp[2]), 'utf-8')
			if name == 'unsorted':
				query = Article.all().filter('has_category =', False).order('-time_stamp')
			else:
				query = Category.all().filter('name =', name)
				if query.get() != None:
					query = query.get().articles.order('-time_stamp')

		elif key == 'tag':
			if len(temp) == 4 or len(temp) > 3 and temp[3] != 'page':
				path = os.path.join(os.path.dirname(__file__), 'pages/error.html')
				self.response.out.write(template.render(path, None))
				return

			name = unicode(urllib.unquote(temp[2]), 'utf-8')
			query = Tag.all().filter('name =', name)
			if query.get() != None:
				query = query.get().ref_tag.order('-time_stamp')

		else:
			year = int(temp[2])
			month = int(temp[3])
			pageno = 1
			if len(temp) > 4:
				try:
					pageno = int(temp[-1])
				except ValueError:
					pageno = 1

			name = str(year) + '/' + str(month)
			query = db.GqlQuery('select * from Archive where year = :1 and month = :2',
								 year, month)
			if query.get() != None:
				query = query.get().articles.order('-time_stamp')
			

		group = query.fetch(1000)

		article_list = []
		pagei = 0
		start = 0
		length = len(group)

		while group != [] and article_list == []:
			# Pick out each page
			while start + self.article_per_page - 1 < length:
				pagei = pagei + 1
				if pagei == pageno:
					article_list = group[start : start + self.article_per_page]
				start = start + self.article_per_page
			if len(group[start : start + self.article_per_page]) > 0:
				pagei = pagei + 1
				if pagei == pageno:
					article_list = group[start : start + self.article_per_page]

			last_time = group[-1].time_stamp
			query.filter('time_stamp <', last_time)
			group = query.fetch(1000)

		show_left_arrow = 1 if pageno > 1 else 0
		show_right_arrow = 1 if pageno < pagei else 0
		show_left_dot = 1 if pageno >= 5 else 0
		show_right_dot = 1 if pageno <= pagei - 4 else 0

		pageno_list = [i for i in range(max(1, pageno - 3), min(pagei + 1, pageno + 4))]

		if key == 'tag':
			article_set = []
			for item in article_list:
				article_set.append(item.article)

		template_values = {
			'articles': article_list if key != 'tag' else article_set,
			'pagename': 'articles',
			'page_current': pageno,
			'page_total': pagei,
			'pageno_list': pageno_list,
			'show_left_arrow': show_left_arrow,
			'show_right_arrow': show_right_arrow,
			'show_left_dot': show_left_dot,
			'show_right_dot': show_right_dot,
			'colno': len(pageno_list) + show_left_arrow + show_right_arrow + 
			                           show_left_dot + show_right_dot,
			'page_prev': max(1, pageno - 1),
			'page_next': min(pagei, pageno + 1),
			'categories': get_all_categories(),
			'tags': get_all_tags(),
			'name': name,
			'key': key,
			'unsorted_count': count_unsorted(),
		}

		path = os.path.join(os.path.dirname(__file__), 'pages/articles.html')
		self.response.headers['Content-Type'] = 'text/html;charset=utf-8'
		self.response.out.write(template.render(path, template_values))